HRB_Bluetooth.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. using ArduinoBluetoothAPI;
  2. using System;
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. using UnityEngine.UI;
  6. using DG.Tweening;
  7. /* 蓝牙瞄准模块 */
  8. public class HRB_Bluetooth : MonoBehaviour
  9. {
  10. readonly string targetDeviceName = "Bbow_20210501";
  11. string targetDeviceService {
  12. get {
  13. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3) {
  14. #if UNITY_ANDROID
  15. return "0000fff0";
  16. #else
  17. return "fff0";
  18. #endif
  19. }
  20. return "6e400001";
  21. }
  22. }
  23. string targetDeviceCharacteristicWrite {
  24. get {
  25. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3) {
  26. #if UNITY_ANDROID
  27. return "0000fff2";
  28. #else
  29. return "fff2";
  30. #endif
  31. }
  32. return "6e400002";
  33. }
  34. }
  35. string targetDeviceCharacteristicNotify {
  36. get {
  37. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3) {
  38. #if UNITY_ANDROID
  39. return "0000fff1";
  40. #else
  41. return "fff1";
  42. #endif
  43. }
  44. return "6e400003";
  45. }
  46. }
  47. BluetoothHelper bluetoothHelper;
  48. BluetoothHelperCharacteristic characteristicWrite;
  49. BluetoothHelperService bluetoothService;
  50. string deviceName = "";
  51. bool canConnect = true;
  52. [SerializeField] Text textUI;
  53. public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
  54. public Action onFindTargetDevice;
  55. void OnDestroy()
  56. {
  57. DisconnectBleHelper();
  58. }
  59. private bool userDoConnect = false;
  60. private bool doConnect = false;
  61. public Func<bool> action_DoConnectInterceptor;
  62. public void DoConnect()
  63. {
  64. if (action_DoConnectInterceptor != null) {
  65. if (action_DoConnectInterceptor.Invoke()) return;
  66. }
  67. if (status == BluetoothStatusEnum.Connect)
  68. {
  69. userDoConnect = true;
  70. doConnect = true;
  71. SetStatus(BluetoothStatusEnum.Connecting);
  72. }
  73. else if (status == BluetoothStatusEnum.ConnectSuccess)
  74. {
  75. userDoConnect = false;
  76. doConnect = false;
  77. OnDisconnect();
  78. DisconnectBleHelper();
  79. }
  80. }
  81. void OnDisconnect()
  82. {
  83. canConnect = true;
  84. SetStatus(BluetoothStatusEnum.ConnectFail);
  85. BowCamera.isTouchMode = true;
  86. if (AimHandler.ins) AimHandler.ins.SetMsOldDefault();
  87. }
  88. void Update()
  89. {
  90. if (userDoConnect && status == BluetoothStatusEnum.Connect)
  91. {
  92. DoConnect();
  93. }
  94. if (doConnect) Connect();
  95. }
  96. void SetStatus(BluetoothStatusEnum statusValue)
  97. {
  98. status = statusValue;
  99. if (status == BluetoothStatusEnum.ConnectFail)
  100. {
  101. Sequence sequence = DOTween.Sequence();
  102. sequence.AppendInterval(2f);
  103. sequence.AppendCallback(delegate ()
  104. {
  105. if (status == BluetoothStatusEnum.ConnectFail)
  106. {
  107. status = BluetoothStatusEnum.Connect;
  108. }
  109. });
  110. sequence.SetUpdate(true);
  111. SimulateMouseController.ins?.SetBleConnected(false);
  112. } else if (status == BluetoothStatusEnum.ConnectSuccess) {
  113. SimulateMouseController.ins?.SetBleConnected(true);
  114. }
  115. }
  116. void DisconnectBleHelper()
  117. {
  118. if (bluetoothHelper != null) bluetoothHelper.Disconnect();
  119. }
  120. void Connect()
  121. {
  122. if (BluetoothShoot.scanLock)
  123. {
  124. return;
  125. }
  126. if (!canConnect)
  127. {
  128. return;
  129. }
  130. doConnect = false;
  131. canConnect = false;
  132. SetStatus(BluetoothStatusEnum.Connecting);
  133. ConnectBleHelper();
  134. }
  135. void ConnectBleHelper()
  136. {
  137. try
  138. {
  139. #if UNITY_ANDROID
  140. using (var helper = new AndroidJavaClass("com.example.smartbowlib.BluetoothHelper"))
  141. {
  142. using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
  143. {
  144. using (var context = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
  145. {
  146. bool ok = helper.CallStatic<bool>("requestPermissions", context);
  147. if (!ok) throw new Exception("安卓12的蓝牙权限-尚未授权");
  148. }
  149. }
  150. }
  151. #endif
  152. BluetoothHelper.BLE = true;
  153. bluetoothHelper = BluetoothHelper.GetNewInstance();
  154. bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
  155. {
  156. Log("连接成功\n" + helper.getDeviceName());
  157. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  158. BowCamera.isTouchMode = false;
  159. foreach (BluetoothHelperService service in helper.getGattServices())
  160. {
  161. if (service.getName().ToLower().StartsWith(targetDeviceService))
  162. {
  163. bluetoothService = service;
  164. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  165. {
  166. if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicWrite))
  167. {
  168. characteristicWrite = characteristic;
  169. }
  170. else if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicNotify))
  171. {
  172. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  173. ch.setService(bluetoothService.getName());
  174. bluetoothHelper.Subscribe(ch);
  175. }
  176. }
  177. }
  178. }
  179. };
  180. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  181. {
  182. Log("连接失败\n" + helper.getDeviceName());
  183. OnDisconnect();
  184. };
  185. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  186. {
  187. if (status != BluetoothStatusEnum.ConnectSuccess) return;
  188. };
  189. int scanCount = 0;
  190. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  191. {
  192. foreach (BluetoothDevice device in nearbyDevices)
  193. {
  194. Log("发现设备 " + device.DeviceName);
  195. if (device.DeviceName == targetDeviceName)
  196. {
  197. deviceName = device.DeviceName;
  198. // bluetoothHelper.setDeviceName(deviceName);
  199. // bluetoothHelper.Connect();
  200. Log("匹配设备 " + device.DeviceName);
  201. onFindTargetDevice?.Invoke();
  202. return;
  203. }
  204. }
  205. if (scanCount < 3)
  206. { //如果没扫描到,则重新扫描,达到延迟提示失败的效果
  207. scanCount++;
  208. bluetoothHelper.ScanNearbyDevices();
  209. }
  210. else
  211. {
  212. canConnect = true;
  213. Log("没有发现设备");
  214. SetStatus(BluetoothStatusEnum.ConnectFail);
  215. }
  216. };
  217. bluetoothHelper.ScanNearbyDevices();
  218. Log("正在扫描设备");
  219. }
  220. catch (Exception e)
  221. {
  222. Debug.LogError(e.Message);
  223. Debug.LogError(e.StackTrace);
  224. canConnect = true;
  225. status = BluetoothStatusEnum.Connect;
  226. userDoConnect = false;
  227. PopupMgr.ins.ShowTip(TextAutoLanguage2.GetTextByKey("ble-please-open-ble"));
  228. }
  229. }
  230. void Log(string text)
  231. {
  232. if (textUI) textUI.text = text;
  233. Debug.Log(string.Format("[{0}]{1}", typeof(HRB_Bluetooth).Name, text));
  234. }
  235. }