BluetoothAim.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. using ArduinoBluetoothAPI;
  2. using System;
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using UnityEngine.UI;
  7. public class BluetoothAim : MonoBehaviour
  8. {
  9. BluetoothHelper bluetoothHelper;
  10. BluetoothHelperCharacteristic characteristicWrite;
  11. BluetoothHelperService bluetoothService;
  12. string deviceName = "";
  13. bool canConnect = true;
  14. [SerializeField] string targetDeviceName = "Bbow_20210501";
  15. [SerializeField] Text textUI;
  16. [SerializeField] Transform controlObj = default;
  17. [SerializeField] Button SetIdentity = default;
  18. [SerializeField] Button MagCalibrationButton = default;
  19. [SerializeField] Button GyrCalibrationButton = default;
  20. [SerializeField] Text MagScaleText = default;
  21. [SerializeField] Text GyrScaleText = default;
  22. AimHandler aimHandler = null;
  23. public static bool scanLock = false; //防止同时扫描冲突
  24. void Start()
  25. {
  26. aimHandler = new AimHandler(controlObj, SetIdentity, MagCalibrationButton, GyrCalibrationButton, MagScaleText, GyrScaleText);
  27. BluetoothDispatcher.aim = aimHandler.OnDataReceived;
  28. }
  29. void OnDestroy()
  30. {
  31. if (bluetoothHelper != null)
  32. {
  33. bluetoothHelper.Disconnect();
  34. }
  35. }
  36. void FixedUpdate()
  37. {
  38. Connect();
  39. }
  40. void Update()
  41. {
  42. aimHandler.Update();
  43. }
  44. void Connect()
  45. {
  46. if (BluetoothShoot.scanLock)
  47. {
  48. return;
  49. }
  50. if (!canConnect)
  51. {
  52. return;
  53. }
  54. scanLock = true;
  55. canConnect = false;
  56. try
  57. {
  58. BluetoothHelper.BLE = true;
  59. bluetoothHelper = BluetoothHelper.GetNewInstance();
  60. bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
  61. {
  62. Log("连接成功\n" + helper.getDeviceName());
  63. foreach (BluetoothHelperService service in helper.getGattServices())
  64. {
  65. if (service.getName().ToLower().StartsWith("0000fff0"))
  66. {
  67. bluetoothService = service;
  68. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  69. {
  70. if (characteristic.getName().ToLower().StartsWith("0000fff2"))
  71. {
  72. characteristicWrite = characteristic;
  73. }
  74. else if (characteristic.getName().ToLower().StartsWith("0000fff1"))
  75. {
  76. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  77. ch.setService(bluetoothService.getName());
  78. bluetoothHelper.Subscribe(ch);
  79. }
  80. }
  81. }
  82. }
  83. Invoke("OpenReceiveData", 1);
  84. };
  85. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  86. {
  87. canConnect = true;
  88. Log("连接失败\n" + helper.getDeviceName());
  89. };
  90. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  91. {
  92. byte[] bytes = value;
  93. // Log(String.Join(",", bytes));
  94. BluetoothClient.UploadData(0, bytes);
  95. aimHandler.OnDataReceived(bytes);
  96. };
  97. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  98. {
  99. scanLock = false;
  100. foreach (BluetoothDevice device in nearbyDevices)
  101. {
  102. if (device.DeviceName == targetDeviceName)
  103. {
  104. deviceName = device.DeviceName;
  105. bluetoothHelper.setDeviceName(deviceName);
  106. bluetoothHelper.Connect();
  107. Log("发现设备\n" + device.DeviceName);
  108. return;
  109. }
  110. }
  111. canConnect = true;
  112. Log("没有发现设备");
  113. };
  114. bluetoothHelper.ScanNearbyDevices();
  115. Log("正在扫描设备");
  116. }
  117. catch (Exception e)
  118. {
  119. Debug.Log(e.Message);
  120. canConnect = true;
  121. Log("请打开蓝牙");
  122. }
  123. }
  124. void OpenReceiveData()
  125. {
  126. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  127. ch.setService(bluetoothService.getName());
  128. bluetoothHelper.WriteCharacteristic(ch, "3");
  129. Log("瞄准模块准备完成\n" + deviceName);
  130. }
  131. void Log(string text)
  132. {
  133. if (textUI != null)
  134. {
  135. textUI.text = text;
  136. }
  137. }
  138. public void SetControlObject(Transform obj)
  139. {
  140. this.aimHandler.controlObj = obj;
  141. if (obj != null)
  142. {
  143. this.aimHandler.InitAutoIdentity();
  144. }
  145. }
  146. }
  147. class AimHandler
  148. {
  149. public Transform controlObj;
  150. Button SetIdentity = default;
  151. Button MagCalibrationButton = default;
  152. Button GyrCalibrationButton = default;
  153. Text MagScaleText = default;
  154. Text GyrScaleText = default;
  155. long TimeGap = default;
  156. Vector3 Acc = default;
  157. Vector3 Gyr = default;
  158. Vector3 Mag = default;
  159. o09Axis _9Axis = new o09Axis();
  160. //转换读取的数据,无符号->有符号
  161. float TwoByteToFloat(byte b1, byte b2)
  162. {
  163. ushort twoByte = (ushort) (b1 * 256 + b2);
  164. short shortNum = (short) twoByte;
  165. return (float) shortNum;
  166. }
  167. o0MagneticCalibraterSimple MagCalibrater;
  168. o0GyrCalibrater GyrCalibrater;
  169. long msOld = 0;
  170. public AimHandler(
  171. Transform controlObj,
  172. Button SetIdentity,
  173. Button MagCalibrationButton,
  174. Button GyrCalibrationButton,
  175. Text MagScaleText,
  176. Text GyrScaleText
  177. ) {
  178. this.controlObj = controlObj;
  179. this.SetIdentity = SetIdentity;
  180. this.MagCalibrationButton = MagCalibrationButton;
  181. this.GyrCalibrationButton = GyrCalibrationButton;
  182. this.MagScaleText = MagScaleText;
  183. this.GyrScaleText = GyrScaleText;
  184. if (SetIdentity != null)
  185. {
  186. SetIdentity.onClick.AddListener(DoIdentity);
  187. }
  188. MagCalibrater = new o0MagneticCalibraterSimple();
  189. string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  190. if (magDataStr.Length > 0)
  191. {
  192. string[] dataStrs = magDataStr.Split(',');
  193. if (dataStrs.Length == 6)
  194. {
  195. MagCalibrater._Center = new Vector3(float.Parse(dataStrs[0]), float.Parse(dataStrs[1]), float.Parse(dataStrs[2]));
  196. MagCalibrater._Radius = new Vector3(float.Parse(dataStrs[3]), float.Parse(dataStrs[4]), float.Parse(dataStrs[5]));
  197. }
  198. }
  199. if (MagCalibrationButton != null)
  200. {
  201. MagCalibrationButton.onClick.AddListener(delegate {
  202. if (MagCalibrater.Calibration)
  203. {
  204. MagCalibrater.Calibration = false;
  205. MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  206. float[] dataFloats = new float[6];
  207. dataFloats[0] = MagCalibrater.Center.x;
  208. dataFloats[1] = MagCalibrater.Center.y;
  209. dataFloats[2] = MagCalibrater.Center.z;
  210. dataFloats[3] = MagCalibrater.Radius.x;
  211. dataFloats[4] = MagCalibrater.Radius.y;
  212. dataFloats[5] = MagCalibrater.Radius.z;
  213. string dataStr = String.Join(",", dataFloats);
  214. PlayerPrefs.SetString("o0MagneticCalibrater", dataStr);
  215. }
  216. else
  217. {
  218. MagCalibrater.Calibration = true;
  219. MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  220. }
  221. });
  222. }
  223. GyrCalibrater = new o0GyrCalibrater();
  224. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  225. if (gyrDataStr.Length > 0)
  226. {
  227. string[] dataStrs = gyrDataStr.Split(',');
  228. if (dataStrs.Length == 3)
  229. {
  230. GyrCalibrater._Average = new Vector3(float.Parse(dataStrs[0]), float.Parse(dataStrs[1]), float.Parse(dataStrs[2]));
  231. }
  232. }
  233. if (GyrCalibrationButton != null)
  234. {
  235. GyrCalibrationButton.onClick.AddListener(delegate {
  236. if (GyrCalibrater.Calibration)
  237. {
  238. GyrCalibrater.Calibration = false;
  239. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  240. float[] dataFloats = new float[3];
  241. dataFloats[0] = GyrCalibrater._Average.x;
  242. dataFloats[1] = GyrCalibrater._Average.y;
  243. dataFloats[2] = GyrCalibrater._Average.z;
  244. string dataStr = String.Join(",", dataFloats);
  245. PlayerPrefs.SetString("o0GyrCalibrater", dataStr);
  246. }
  247. else
  248. {
  249. GyrCalibrater.Calibration = true;
  250. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  251. }
  252. });
  253. }
  254. }
  255. public void OnDataReceived(byte[] bytes)
  256. {
  257. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  258. if (bytes.Length != 26)
  259. {
  260. if (bytes[3] == 125)
  261. {
  262. DoIdentity();
  263. }
  264. return;
  265. }
  266. if (bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0)
  267. return;
  268. if (bytes[16] == 0 && bytes[17] == 0 && bytes[18] == 0 && bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0)
  269. return;
  270. float ax = -TwoByteToFloat(bytes[4], bytes[5]);
  271. float ay = TwoByteToFloat(bytes[6], bytes[7]);
  272. float az = -TwoByteToFloat(bytes[8], bytes[9]);
  273. ax = ax / 32768 * 16;
  274. ay = ay / 32768 * 16;
  275. az = az / 32768 * 16;
  276. Acc = new Vector3(ax, ay, az);
  277. float roll = TwoByteToFloat(bytes[10], bytes[11]);
  278. float pitch = TwoByteToFloat(bytes[12], bytes[13]);
  279. float yaw = TwoByteToFloat(bytes[14], bytes[15]);
  280. roll = -roll / 32768 * 2000;
  281. pitch = pitch / 32768 * 2000;
  282. yaw = -yaw / 32768 * 2000;
  283. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  284. Gyr = GyrCalibrater.Update(Gyr);
  285. if (GyrScaleText != null)
  286. {
  287. GyrScaleText.text = GyrCalibrater._Average.x + "\n" + GyrCalibrater._Average.y + "\n" + GyrCalibrater._Average.z;
  288. }
  289. float x = TwoByteToFloat(bytes[16], bytes[17]);
  290. float y = TwoByteToFloat(bytes[18], bytes[19]);
  291. float z = -TwoByteToFloat(bytes[20], bytes[21]);
  292. var mag = new Vector3(x, y, z);
  293. Mag = mag / 32768 * 256;
  294. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  295. {
  296. Mag = MagCalibrater.Update(Mag);
  297. if (MagScaleText != null)
  298. {
  299. MagScaleText.text = MagCalibrater._Radius.ToString() + MagCalibrater.CalibratCompletionPercentage() + "%";
  300. }
  301. }
  302. var ms = (((long)bytes[22]) *60 + bytes[23])*1000 + (long)TwoByteToFloat(bytes[1], bytes[2]);
  303. if(msOld == default)
  304. {
  305. msOld = ms;
  306. return;
  307. }
  308. TimeGap = ms - msOld;
  309. msOld = ms;
  310. newRotation = _9Axis.Update(Acc * 10, Gyr, Mag, TimeGap);
  311. receiveDataCount++;
  312. if (!hasAutoIdentity && receiveDataCount == 5) {
  313. doIdentity = true;
  314. }
  315. }
  316. void DoIdentity()
  317. {
  318. if (hasAutoIdentity)
  319. {
  320. doIdentity = true;
  321. Debug.Log("reset identity");
  322. }
  323. }
  324. public void Update()
  325. {
  326. if (hasAutoIdentity && controlObj != null)
  327. {
  328. // controlObj.localRotation = Quaternion.Lerp(controlObj.localRotation, newRotation, Time.deltaTime * 6);
  329. controlObj.localRotation = newRotation;
  330. GameObject.Find("Canvas/RPY_LOG").GetComponent<Text>().text =
  331. "roll: " + controlObj.localEulerAngles.x +
  332. "\npitch: " + controlObj.localEulerAngles.y +
  333. "\nyaw: " + controlObj.localEulerAngles.z;
  334. }
  335. if (doIdentity)
  336. {
  337. _9Axis.SetIdentityAccordingToRecords();
  338. if (controlObj != null)
  339. {
  340. controlObj.localRotation = Quaternion.identity;
  341. }
  342. doIdentity = false;
  343. hasAutoIdentity = true;
  344. }
  345. }
  346. int receiveDataCount = 0;
  347. bool doIdentity = false;
  348. bool hasAutoIdentity = false;
  349. Quaternion newRotation;
  350. public void InitAutoIdentity()
  351. {
  352. receiveDataCount = 0;
  353. doIdentity = false;
  354. hasAutoIdentity = false;
  355. }
  356. }