BluetoothAim.cs 16 KB

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