BluetoothAim.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. [SerializeField] public Transform testEllipse;
  25. [SerializeField] public Transform testEllipseToggle;
  26. AimHandler aimHandler = null;
  27. public static bool scanLock = false; //防止同时扫描冲突
  28. void Start()
  29. {
  30. aimHandler = new AimHandler(controlObj, SetIdentity, MagCalibrationButton, GyrCalibrationButton, MagScaleText, GyrScaleText, testEllipse, testEllipseToggle);
  31. BluetoothDispatcher.aim = aimHandler.OnDataReceived;
  32. }
  33. void OnDestroy()
  34. {
  35. if (bluetoothHelper != null)
  36. {
  37. bluetoothHelper.Disconnect();
  38. }
  39. }
  40. void FixedUpdate()
  41. {
  42. Connect();
  43. }
  44. void Update()
  45. {
  46. aimHandler.Update();
  47. }
  48. void Connect()
  49. {
  50. if (BluetoothShoot.scanLock)
  51. {
  52. return;
  53. }
  54. if (!canConnect)
  55. {
  56. return;
  57. }
  58. scanLock = true;
  59. canConnect = false;
  60. try
  61. {
  62. BluetoothHelper.BLE = true;
  63. bluetoothHelper = BluetoothHelper.GetNewInstance();
  64. bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
  65. {
  66. Log("连接成功\n" + helper.getDeviceName());
  67. foreach (BluetoothHelperService service in helper.getGattServices())
  68. {
  69. if (service.getName().ToLower().StartsWith("0000fff0"))
  70. {
  71. bluetoothService = service;
  72. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  73. {
  74. if (characteristic.getName().ToLower().StartsWith("0000fff2"))
  75. {
  76. characteristicWrite = characteristic;
  77. }
  78. else if (characteristic.getName().ToLower().StartsWith("0000fff1"))
  79. {
  80. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  81. ch.setService(bluetoothService.getName());
  82. bluetoothHelper.Subscribe(ch);
  83. }
  84. }
  85. }
  86. }
  87. Invoke("OpenReceiveData", 1);
  88. };
  89. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  90. {
  91. canConnect = true;
  92. Log("连接失败\n" + helper.getDeviceName());
  93. };
  94. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  95. {
  96. byte[] bytes = value;
  97. // Log(String.Join(",", bytes));
  98. BluetoothClient.UploadData(0, bytes);
  99. aimHandler.OnDataReceived(bytes);
  100. };
  101. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  102. {
  103. scanLock = false;
  104. foreach (BluetoothDevice device in nearbyDevices)
  105. {
  106. if (device.DeviceName == targetDeviceName)
  107. {
  108. deviceName = device.DeviceName;
  109. bluetoothHelper.setDeviceName(deviceName);
  110. bluetoothHelper.Connect();
  111. Log("发现设备\n" + device.DeviceName);
  112. return;
  113. }
  114. }
  115. canConnect = true;
  116. Log("没有发现设备");
  117. };
  118. bluetoothHelper.ScanNearbyDevices();
  119. Log("正在扫描设备");
  120. }
  121. catch (Exception e)
  122. {
  123. Debug.Log(e.Message);
  124. canConnect = true;
  125. Log("请打开蓝牙");
  126. }
  127. }
  128. void OpenReceiveData()
  129. {
  130. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  131. ch.setService(bluetoothService.getName());
  132. bluetoothHelper.WriteCharacteristic(ch, "3");
  133. Log("瞄准模块准备完成\n" + deviceName);
  134. }
  135. void Log(string text)
  136. {
  137. if (textUI != null)
  138. {
  139. textUI.text = text;
  140. }
  141. }
  142. public void SetControlObject(Transform obj)
  143. {
  144. this.aimHandler.controlObj = obj;
  145. if (obj != null)
  146. {
  147. this.aimHandler.InitAutoIdentity();
  148. }
  149. }
  150. }
  151. class AimHandler
  152. {
  153. public Transform controlObj;
  154. Button SetIdentity = default;
  155. Button MagCalibrationButton = default;
  156. Button GyrCalibrationButton = default;
  157. Text MagScaleText = default;
  158. Text GyrScaleText = default;
  159. long TimeGap = default;
  160. Vector3 Acc = default;
  161. Vector3 Gyr = default;
  162. Vector3 Mag = default;
  163. o09Axis _9Axis = new o09Axis();
  164. o0SigmoidIntegrationFilterQuaternion filter = new o0SigmoidIntegrationFilterQuaternion(0.2f);
  165. //椭圆对象
  166. Transform testEllipse;
  167. public Ellipse ellipseScript;
  168. public Toggle ellipseToggle;
  169. Vector3 cMaxVector = new Vector3(0,0,0);
  170. Vector3 cMinVector = new Vector3(0, 0, 0);
  171. //转换读取的数据,无符号->有符号
  172. float TwoByteToFloat(byte b1, byte b2)
  173. {
  174. ushort twoByte = (ushort) (b1 * 256 + b2);
  175. short shortNum = (short) twoByte;
  176. return (float) shortNum;
  177. }
  178. // o0MagneticCalibraterSimple MagCalibrater;
  179. o0MagneticCalibraterEllipsoidFitting MagCalibrater;
  180. o0GyrCalibrater GyrCalibrater;
  181. long msOld = 0;
  182. public AimHandler(
  183. Transform controlObj,
  184. Button SetIdentity,
  185. Button MagCalibrationButton,
  186. Button GyrCalibrationButton,
  187. Text MagScaleText,
  188. Text GyrScaleText,
  189. //椭圆对象
  190. Transform testEllipse,
  191. Transform testToggle
  192. ) {
  193. this.controlObj = controlObj;
  194. this.SetIdentity = SetIdentity;
  195. this.MagCalibrationButton = MagCalibrationButton;
  196. this.GyrCalibrationButton = GyrCalibrationButton;
  197. this.MagScaleText = MagScaleText;
  198. this.GyrScaleText = GyrScaleText;
  199. //椭圆对象
  200. this.testEllipse = testEllipse;
  201. this.ellipseScript = this.testEllipse.gameObject.GetComponent<Ellipse>();
  202. this.ellipseToggle = testToggle.gameObject.GetComponent<Toggle>();
  203. this.ellipseToggle.onValueChanged.AddListener(OnValueChanged);
  204. if (SetIdentity != null)
  205. {
  206. SetIdentity.onClick.AddListener(DoIdentity);
  207. }
  208. // MagCalibrater = new o0MagneticCalibraterSimple();
  209. // string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  210. // if (magDataStr.Length > 0)
  211. // {
  212. // string[] dataStrs = magDataStr.Split(',');
  213. // if (dataStrs.Length == 6)
  214. // {
  215. // MagCalibrater._Center = new Vector3(float.Parse(dataStrs[0]), float.Parse(dataStrs[1]), float.Parse(dataStrs[2]));
  216. // MagCalibrater._Radius = new Vector3(float.Parse(dataStrs[3]), float.Parse(dataStrs[4]), float.Parse(dataStrs[5]));
  217. // }
  218. // }
  219. // if (MagCalibrationButton != null)
  220. // {
  221. // MagCalibrationButton.onClick.AddListener(delegate {
  222. // // if (MagCalibrater.Calibration)
  223. // if (MagCalibrater.Calibration)
  224. // {
  225. // Debug.Log(MagCalibrater.Calibration);
  226. // MagCalibrater.Calibration = false;
  227. // Debug.Log(MagCalibrater.Calibration);
  228. // MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  229. // float[] dataFloats = new float[6];
  230. // dataFloats[0] = MagCalibrater.Center.x;
  231. // dataFloats[1] = MagCalibrater.Center.y;
  232. // dataFloats[2] = MagCalibrater.Center.z;
  233. // dataFloats[3] = MagCalibrater.Radius.x;
  234. // dataFloats[4] = MagCalibrater.Radius.y;
  235. // dataFloats[5] = MagCalibrater.Radius.z;
  236. // string dataStr = String.Join(",", dataFloats);
  237. // PlayerPrefs.SetString("o0MagneticCalibrater", dataStr);
  238. // }
  239. // else
  240. // {
  241. // Debug.Log(MagCalibrater.Calibration);
  242. // MagCalibrater.Calibration = true;
  243. // Debug.Log(MagCalibrater.Calibration);
  244. // MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  245. // }
  246. // });
  247. // }
  248. try {
  249. string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  250. MagCalibrater = JsonConvert.DeserializeObject<o0MagneticCalibraterEllipsoidFitting>(magDataStr);
  251. //List<Vector3> list = MagCalibrater.getRecords();
  252. //this.ellipseScript.DrawPointCloud(list);
  253. //this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center);
  254. } catch(Exception) {
  255. MagCalibrater = null;
  256. }
  257. if (MagCalibrater == null)
  258. {
  259. MagCalibrater = new o0MagneticCalibraterEllipsoidFitting();
  260. }
  261. if (MagCalibrationButton != null)
  262. {
  263. MagCalibrationButton.onClick.AddListener(delegate {
  264. if (MagCalibrater.Calibration)
  265. {
  266. List<Vector3> list = MagCalibrater.getRecords();
  267. //停止校准时候,看看数组值
  268. float maxDistance = 0f,ratio = 1f;
  269. Vector3 maxVector3 = new Vector3(0,0,0);
  270. List<Vector3> endRecords = new List<Vector3>();
  271. foreach (Vector3 i in list)
  272. {
  273. Vector3 v = i - MagCalibrater._Center;
  274. if (Math.Abs(v.magnitude) > maxDistance)
  275. {
  276. maxVector3 = v;
  277. maxDistance = Math.Abs(v.magnitude);
  278. if(Math.Abs(v.magnitude) < Math.Abs(MagCalibrater._Radius.magnitude))
  279. ratio = Math.Abs(v.magnitude) / Math.Abs(MagCalibrater._Radius.magnitude);
  280. else
  281. ratio = Math.Abs(MagCalibrater._Radius.magnitude) / Math.Abs(v.magnitude);
  282. }
  283. }
  284. Debug.LogWarning(maxDistance + " == " + Math.Abs(MagCalibrater._Radius.magnitude) + " == " + MagCalibrater._Radius + " = " + maxVector3);
  285. //如果比例效果不理想。可以设置为ratio=0.5f
  286. foreach (Vector3 i in list)
  287. {
  288. //- MagCalibrater._Center
  289. Vector3 v = i ;
  290. v *= ratio;
  291. endRecords.Add(v);
  292. }
  293. this.ellipseScript.ClearAndUpdatePointArray();
  294. this.ellipseScript.DrawPointCloud(endRecords);
  295. //绘制椭圆形
  296. if (MagCalibrater._Radius != this.ellipseScript.ellipseTran.localScale)
  297. {
  298. this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center* ratio);
  299. //设置绘制图像相机的对应位置
  300. this.ellipseScript.setCameraPos(MagCalibrater._Center * 0.5f);
  301. }
  302. MagCalibrater.Calibration = false;
  303. MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  304. PlayerPrefs.SetString("o0MagneticCalibrater", JsonConvert.SerializeObject(MagCalibrater));
  305. }
  306. else
  307. {
  308. MagCalibrater.Calibration = true;
  309. MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  310. this.cMaxVector = new Vector3(0, 0, 0);
  311. this.cMinVector = new Vector3(0, 0, 0);
  312. }
  313. });
  314. }
  315. try {
  316. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  317. GyrCalibrater = JsonConvert.DeserializeObject<o0GyrCalibrater>(gyrDataStr);
  318. if (GyrCalibrater._Average != Vector3.zero) GyrScaleText.text = "已校准";
  319. } catch(Exception) {
  320. GyrCalibrater = null;
  321. }
  322. if (GyrCalibrater == null)
  323. {
  324. GyrCalibrater = new o0GyrCalibrater();
  325. }
  326. if (GyrCalibrationButton != null)
  327. {
  328. GyrCalibrationButton.onClick.AddListener(delegate {
  329. if (GyrCalibrater.Calibration)
  330. {
  331. GyrCalibrater.Calibration = false;
  332. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  333. PlayerPrefs.SetString("o0GyrCalibrater", JsonConvert.SerializeObject(GyrCalibrater));
  334. }
  335. else
  336. {
  337. GyrCalibrater.Calibration = true;
  338. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  339. }
  340. });
  341. }
  342. }
  343. private void OnValueChanged(bool value)
  344. {
  345. if (value)
  346. {
  347. //选中了的逻辑
  348. }
  349. Debug.Log(value);
  350. }
  351. public void OnDataReceived(byte[] bytes)
  352. {
  353. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  354. if (bytes.Length != 26)
  355. {
  356. if (bytes[3] == 125)
  357. {
  358. DoIdentity();
  359. }
  360. return;
  361. }
  362. if (bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0)
  363. return;
  364. if (bytes[16] == 0 && bytes[17] == 0 && bytes[18] == 0 && bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0)
  365. return;
  366. float ax = -TwoByteToFloat(bytes[4], bytes[5]);
  367. float ay = TwoByteToFloat(bytes[6], bytes[7]);
  368. float az = -TwoByteToFloat(bytes[8], bytes[9]);
  369. ax = ax / 32768 * 16;
  370. ay = ay / 32768 * 16;
  371. az = az / 32768 * 16;
  372. Acc = new Vector3(ax, ay, az);
  373. float roll = TwoByteToFloat(bytes[10], bytes[11]);
  374. float pitch = TwoByteToFloat(bytes[12], bytes[13]);
  375. float yaw = TwoByteToFloat(bytes[14], bytes[15]);
  376. roll = -roll / 32768 * 2000;
  377. pitch = pitch / 32768 * 2000;
  378. yaw = -yaw / 32768 * 2000;
  379. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  380. Gyr = GyrCalibrater.Update(Gyr);
  381. if (GyrScaleText != null && GyrCalibrater.Calibration)
  382. {
  383. // GyrScaleText.text = GyrCalibrater._Average.x + "\n" + GyrCalibrater._Average.y + "\n" + GyrCalibrater._Average.z;
  384. // GyrScaleText.text = "Gyr*1000,000:" + (_9Axis.GyrOld * 1000000).ToString();
  385. GyrScaleText.text = "" + (_9Axis.GyrOld * 1000000).ToString();
  386. }
  387. float x = TwoByteToFloat(bytes[16], bytes[17]);
  388. float y = TwoByteToFloat(bytes[18], bytes[19]);
  389. float z = -TwoByteToFloat(bytes[20], bytes[21]);
  390. var mag = new Vector3(x, y, z);
  391. Mag = mag / 32768 * 256;
  392. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  393. {
  394. //绘制地磁计点
  395. if (MagCalibrater.Calibration)
  396. {
  397. this.ellipseScript.AddAndUpdatePointArray(Mag);
  398. if (Mag.magnitude > this.cMaxVector.magnitude)
  399. {
  400. this.cMaxVector = Mag;
  401. }
  402. else if (Mag.magnitude < this.cMinVector.magnitude) {
  403. this.cMinVector = Mag;
  404. }
  405. Vector3 _center = this.cMaxVector - this.cMinVector;
  406. Debug.LogWarning(_center + " == "+ _center.magnitude);
  407. //设置绘制图像相机的对应位置
  408. this.ellipseScript.setCameraPos(_center/2);
  409. }
  410. Mag = MagCalibrater.Update(Mag);
  411. if (MagScaleText != null)
  412. {
  413. MagScaleText.text = MagCalibrater._Radius.ToString();
  414. }
  415. }
  416. var ms = (((long)bytes[22]) *60 + bytes[23])*1000 + (long)TwoByteToFloat(bytes[1], bytes[2]);
  417. if(msOld == default)
  418. {
  419. msOld = ms;
  420. return;
  421. }
  422. TimeGap = ms - msOld;
  423. msOld = ms;
  424. newRotation = _9Axis.Update(Acc * 10, Gyr, Mag, TimeGap);
  425. // if(_9Axis.States.Count() < 10){
  426. // newRotation = _9Axis.States.Last().Qua;
  427. // }
  428. // else
  429. // {
  430. // int MuliteLerpCount = 10;
  431. // for (var i = 0;i< MuliteLerpCount;++i)
  432. // {
  433. // newRotation = Quaternion.Slerp(newRotation, _9Axis.States[_9Axis.States.Count() - MuliteLerpCount + i].Qua, 1/(i+1));
  434. // }
  435. // }
  436. receiveDataCount++;
  437. if (!hasAutoIdentity && receiveDataCount == 5) {
  438. doIdentity = true;
  439. }
  440. }
  441. void DoIdentity()
  442. {
  443. if (hasAutoIdentity)
  444. {
  445. doIdentity = true;
  446. Debug.Log("reset identity");
  447. }
  448. }
  449. public void Update()
  450. {
  451. if (hasAutoIdentity && controlObj != null)
  452. {
  453. // controlObj.localRotation = Quaternion.Lerp(controlObj.localRotation, newRotation, Time.deltaTime * 6);
  454. // controlObj.localRotation = newRotation;
  455. Quaternion nowRotation = controlObj.localRotation;
  456. filter.Update(ref nowRotation, newRotation);
  457. controlObj.localRotation = nowRotation;
  458. // GameObject.Find("Canvas/RPY_LOG").GetComponent<Text>().text =
  459. // "roll: " + controlObj.localEulerAngles.x +
  460. // "\npitch: " + controlObj.localEulerAngles.y +
  461. // "\nyaw: " + controlObj.localEulerAngles.z;
  462. GameObject.Find("Canvas/RPY_LOG").GetComponent<Text>().text =
  463. "x: " + _9Axis.States.Last().Qua.eulerAngles.x +
  464. "\ny: " + _9Axis.States.Last().Qua.eulerAngles.y +
  465. "\nz: " + _9Axis.States.Last().Qua.eulerAngles.z;
  466. }
  467. if (doIdentity)
  468. {
  469. _9Axis.SetIdentityAccordingToRecords();
  470. if (controlObj != null)
  471. {
  472. controlObj.localRotation = Quaternion.identity;
  473. }
  474. doIdentity = false;
  475. hasAutoIdentity = true;
  476. }
  477. }
  478. int receiveDataCount = 0;
  479. bool doIdentity = false;
  480. bool hasAutoIdentity = false;
  481. Quaternion newRotation;
  482. public void InitAutoIdentity()
  483. {
  484. receiveDataCount = 0;
  485. doIdentity = false;
  486. hasAutoIdentity = false;
  487. }
  488. }