BluetoothShoot.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using ArduinoBluetoothAPI;
  6. using DG.Tweening;
  7. public class BluetoothShoot : MonoBehaviour
  8. {
  9. BluetoothHelper bluetoothHelper;
  10. BluetoothHelperCharacteristic characteristicWrite;
  11. BluetoothHelperService bluetoothService;
  12. string targetDeviceName = "BArrow_202105";
  13. string deviceName = "";
  14. bool canConnect = true;
  15. [SerializeField] Text textUI;
  16. public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
  17. public bool hasData = false;
  18. public static bool scanLock = false; //防止同时扫描冲突
  19. public static BluetoothShoot ins;
  20. void Start() {
  21. ins = this;
  22. BluetoothDispatcher.shoot = handleDataBytes;
  23. }
  24. void OnDestroy()
  25. {
  26. if (bluetoothHelper != null)
  27. {
  28. bluetoothHelper.Disconnect();
  29. }
  30. }
  31. private bool userDoConnect = false;
  32. private bool doConnect = false;
  33. public void DoConnect() {
  34. if (status == BluetoothStatusEnum.Connect) {
  35. userDoConnect = true;
  36. doConnect = true;
  37. SetStatus(BluetoothStatusEnum.Connecting);
  38. } else if (status == BluetoothStatusEnum.ConnectSuccess) {
  39. userDoConnect = false;
  40. doConnect = false;
  41. OnDisconnect();
  42. bluetoothHelper.Disconnect();
  43. }
  44. }
  45. void OnDisconnect() {
  46. hasData = false;
  47. canConnect = true;
  48. if (ShootCheck.ins) ShootCheck.ins.canAdjustNormalOrHightMode = false;
  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. 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 (BluetoothAim.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, OpenReceiveData);
  117. };
  118. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  119. {
  120. Log("连接失败\n" + helper.getDeviceName());
  121. OnDisconnect();
  122. };
  123. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  124. {
  125. hasData = true;
  126. byte[] bytes = value;
  127. // Log(String.Join(",", bytes));
  128. BluetoothClient.UploadData(1, bytes);
  129. handleDataBytes(bytes);
  130. };
  131. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  132. {
  133. scanLock = false;
  134. foreach (BluetoothDevice device in nearbyDevices)
  135. {
  136. if (device.DeviceName == targetDeviceName)
  137. {
  138. deviceName = device.DeviceName;
  139. bluetoothHelper.setDeviceName(deviceName);
  140. bluetoothHelper.Connect();
  141. Log("发现设备\n" + device.DeviceName);
  142. return;
  143. }
  144. }
  145. canConnect = true;
  146. Log("没有发现设备");
  147. SetStatus(BluetoothStatusEnum.ConnectFail);
  148. };
  149. bluetoothHelper.ScanNearbyDevices();
  150. Log("正在扫描设备");
  151. }
  152. catch (Exception e)
  153. {
  154. Debug.Log(e.Message);
  155. canConnect = true;
  156. Log("请打开蓝牙");
  157. }
  158. }
  159. void OpenReceiveData()
  160. {
  161. WriteData("5");
  162. CallDelay(1, delegate() {
  163. if (ShootCheck.ins)
  164. {
  165. ShootCheck.ins.OnBluetoothReady(this);
  166. Log("射击模块准备完成\n" + deviceName);
  167. }
  168. });
  169. CallDelay(2.5f, delegate() {
  170. WriteData("B");
  171. });
  172. }
  173. void CallDelay(float delayTime, TweenCallback callback)
  174. {
  175. Sequence sequence = DOTween.Sequence();
  176. sequence.PrependInterval(delayTime).AppendCallback(callback);
  177. sequence.SetUpdate(true);
  178. }
  179. public void WriteData(string data)
  180. {
  181. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  182. ch.setService(bluetoothService.getName());
  183. bluetoothHelper.WriteCharacteristic(ch, data);
  184. }
  185. void Log(string text)
  186. {
  187. if (textUI)
  188. {
  189. textUI.text = text;
  190. }
  191. }
  192. bool dataGetting = false;
  193. int dataGetLen = 0;
  194. List<byte> dataBytes = new List<byte>();
  195. int TwoByteToInt(byte b1, byte b2)
  196. {
  197. ushort twoByte = (ushort) (b1 * 256 + b2);
  198. short shortNum = (short) twoByte;
  199. return (int) shortNum;
  200. }
  201. void cacheDataBytes(byte[] bytes, int startIndex) {
  202. for (int i = startIndex; i < bytes.Length; i++) {
  203. byte b = bytes[i];
  204. if (dataBytes.Count < dataGetLen) {
  205. dataBytes.Add(b);
  206. } else {
  207. if (ShootCheck.ins) ShootCheck.ins.OnDataReceived(dataBytes.ToArray());
  208. dataGetting = false;
  209. dataBytes.Clear();
  210. break;
  211. }
  212. }
  213. }
  214. public void handleDataBytes(byte[] bytes) {
  215. if (dataGetting) {
  216. cacheDataBytes(bytes, 0);
  217. } else {
  218. if (bytes.Length >= 5) {
  219. int byte3Value = 0; //轴数据识别,1:x轴,2:y轴,3:z轴
  220. if (ShootCheck.ins) {
  221. CMD cmd = ShootCheck.ins.cmd;
  222. if (cmd.a == "x") byte3Value = 1;
  223. if (cmd.a == "y") byte3Value = 2;
  224. if (cmd.a == "z") byte3Value = 3;
  225. }
  226. if (bytes[0] == 255 || bytes[1] == 255 && bytes[2] == byte3Value) {
  227. dataGetting = true;
  228. dataGetLen = TwoByteToInt(bytes[3], bytes[4]);
  229. cacheDataBytes(bytes, 5);
  230. }
  231. } else if (bytes.Length == 2) {
  232. DeviceBatteryView.ins.RenderBattery(2, bytes[0]);
  233. }
  234. }
  235. }
  236. }