BluetoothAim.cs 15 KB

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