BluetoothAim.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. using ArduinoBluetoothAPI;
  2. using System;
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. using UnityEngine.UI;
  6. using DG.Tweening;
  7. using UnityEngine.SceneManagement;
  8. /* 蓝牙瞄准模块 */
  9. public class BluetoothAim : MonoBehaviour
  10. {
  11. BluetoothHelper bluetoothHelper;
  12. BluetoothHelperCharacteristic characteristicWrite;
  13. BluetoothHelperService bluetoothService;
  14. string targetDeviceName = "Bbow_20210501";
  15. string deviceName = "";
  16. bool canConnect = true;
  17. [SerializeField] Text textUI;
  18. public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
  19. public bool hasData = false;
  20. public long hasDataTime;
  21. public static bool scanLock = false; //防止同时扫描冲突
  22. public static BluetoothAim ins;
  23. void Start() {
  24. ins = this;
  25. }
  26. void OnDestroy()
  27. {
  28. if (bluetoothHelper != null)
  29. {
  30. bluetoothHelper.Disconnect();
  31. }
  32. }
  33. private bool userDoConnect = false;
  34. private bool doConnect = false;
  35. public void DoConnect() {
  36. if (status == BluetoothStatusEnum.Connect) {
  37. userDoConnect = true;
  38. doConnect = true;
  39. SetStatus(BluetoothStatusEnum.Connecting);
  40. } else if (status == BluetoothStatusEnum.ConnectSuccess) {
  41. userDoConnect = false;
  42. doConnect = false;
  43. OnDisconnect();
  44. bluetoothHelper.Disconnect();
  45. }
  46. }
  47. void OnDisconnect() {
  48. hasData = false;
  49. canConnect = true;
  50. SetStatus(BluetoothStatusEnum.ConnectFail);
  51. }
  52. void Update()
  53. {
  54. if (userDoConnect && status == BluetoothStatusEnum.Connect) {
  55. DoConnect();
  56. }
  57. if (doConnect) Connect();
  58. }
  59. void SetStatus(BluetoothStatusEnum statusValue)
  60. {
  61. status = statusValue;
  62. if (status == BluetoothStatusEnum.ConnectFail) {
  63. Sequence sequence = DOTween.Sequence();
  64. sequence.AppendInterval(2f);
  65. sequence.AppendCallback(delegate() {
  66. if (status == BluetoothStatusEnum.ConnectFail) {
  67. status = BluetoothStatusEnum.Connect;
  68. }
  69. });
  70. sequence.SetUpdate(true);
  71. DeviceReconnectView.Show();
  72. }
  73. }
  74. void Connect()
  75. {
  76. if (BluetoothShoot.scanLock)
  77. {
  78. return;
  79. }
  80. if (!canConnect)
  81. {
  82. return;
  83. }
  84. doConnect = false;
  85. scanLock = true;
  86. canConnect = false;
  87. SetStatus(BluetoothStatusEnum.Connecting);
  88. try
  89. {
  90. BluetoothHelper.BLE = true;
  91. bluetoothHelper = BluetoothHelper.GetNewInstance();
  92. bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
  93. {
  94. Log("连接成功\n" + helper.getDeviceName());
  95. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  96. foreach (BluetoothHelperService service in helper.getGattServices())
  97. {
  98. if (service.getName().ToLower().StartsWith("0000fff0"))
  99. {
  100. bluetoothService = service;
  101. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  102. {
  103. if (characteristic.getName().ToLower().StartsWith("0000fff2"))
  104. {
  105. characteristicWrite = characteristic;
  106. }
  107. else if (characteristic.getName().ToLower().StartsWith("0000fff1"))
  108. {
  109. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  110. ch.setService(bluetoothService.getName());
  111. bluetoothHelper.Subscribe(ch);
  112. }
  113. }
  114. }
  115. }
  116. CallDelay(1, OpenInfrared);
  117. CallDelay(2, OpenReceiveData);
  118. CallDelay(3, delegate() {
  119. WriteData(SceneManager.GetActiveScene().name == "Game" ? "b" :"B");
  120. });
  121. };
  122. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  123. {
  124. Log("连接失败\n" + helper.getDeviceName());
  125. OnDisconnect();
  126. };
  127. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  128. {
  129. if (!hasData) hasDataTime = JCUtil.GetTimestamp();
  130. hasData = true;
  131. byte[] bytes = value;
  132. // Log(String.Join(",", bytes));
  133. BluetoothClient.UploadData(0, bytes);
  134. if (AimHandler.ins)
  135. {
  136. AimHandler.ins.OnDataReceived(bytes);
  137. }
  138. };
  139. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  140. {
  141. scanLock = false;
  142. foreach (BluetoothDevice device in nearbyDevices)
  143. {
  144. if (device.DeviceName == targetDeviceName)
  145. {
  146. deviceName = device.DeviceName;
  147. bluetoothHelper.setDeviceName(deviceName);
  148. bluetoothHelper.Connect();
  149. Log("发现设备\n" + device.DeviceName);
  150. return;
  151. }
  152. }
  153. canConnect = true;
  154. Log("没有发现设备");
  155. SetStatus(BluetoothStatusEnum.ConnectFail);
  156. };
  157. bluetoothHelper.ScanNearbyDevices();
  158. Log("正在扫描设备");
  159. }
  160. catch (Exception e)
  161. {
  162. Debug.Log(e.Message);
  163. canConnect = true;
  164. Log("请打开蓝牙");
  165. }
  166. }
  167. void OpenInfrared()
  168. {
  169. WriteData("1");
  170. Log("红外线准备完成\n" + deviceName);
  171. }
  172. void OpenReceiveData()
  173. {
  174. WriteData("3");
  175. Log("瞄准模块准备完成\n" + deviceName);
  176. }
  177. void CallDelay(float delayTime, TweenCallback callback)
  178. {
  179. Sequence sequence = DOTween.Sequence();
  180. sequence.PrependInterval(delayTime).AppendCallback(callback);
  181. sequence.SetUpdate(true);
  182. }
  183. public void WriteData(string data)
  184. {
  185. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  186. ch.setService(bluetoothService.getName());
  187. bluetoothHelper.WriteCharacteristic(ch, data);
  188. }
  189. void Log(string text)
  190. {
  191. if (textUI)
  192. {
  193. textUI.text = text;
  194. }
  195. }
  196. }