BluetoothAim.cs 19 KB

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