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