BluetoothAim.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. //转换读取的数据,无符号->有符号
  170. float TwoByteToFloat(byte b1, byte b2)
  171. {
  172. ushort twoByte = (ushort) (b1 * 256 + b2);
  173. short shortNum = (short) twoByte;
  174. return (float) shortNum;
  175. }
  176. // o0MagneticCalibraterSimple MagCalibrater;
  177. o0MagneticCalibraterEllipsoidFitting MagCalibrater;
  178. o0GyrCalibrater GyrCalibrater;
  179. long msOld = 0;
  180. public AimHandler(
  181. Transform controlObj,
  182. Button SetIdentity,
  183. Button MagCalibrationButton,
  184. Button GyrCalibrationButton,
  185. Text MagScaleText,
  186. Text GyrScaleText,
  187. //椭圆对象
  188. Transform testEllipse,
  189. Transform testToggle
  190. ) {
  191. this.controlObj = controlObj;
  192. this.SetIdentity = SetIdentity;
  193. this.MagCalibrationButton = MagCalibrationButton;
  194. this.GyrCalibrationButton = GyrCalibrationButton;
  195. this.MagScaleText = MagScaleText;
  196. this.GyrScaleText = GyrScaleText;
  197. //椭圆对象
  198. this.testEllipse = testEllipse;
  199. this.ellipseScript = this.testEllipse.gameObject.GetComponent<Ellipse>();
  200. this.ellipseToggle = testToggle.gameObject.GetComponent<Toggle>();
  201. this.ellipseToggle.onValueChanged.AddListener(OnValueChanged);
  202. if (SetIdentity != null)
  203. {
  204. SetIdentity.onClick.AddListener(DoIdentity);
  205. }
  206. // MagCalibrater = new o0MagneticCalibraterSimple();
  207. // string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  208. // if (magDataStr.Length > 0)
  209. // {
  210. // string[] dataStrs = magDataStr.Split(',');
  211. // if (dataStrs.Length == 6)
  212. // {
  213. // MagCalibrater._Center = new Vector3(float.Parse(dataStrs[0]), float.Parse(dataStrs[1]), float.Parse(dataStrs[2]));
  214. // MagCalibrater._Radius = new Vector3(float.Parse(dataStrs[3]), float.Parse(dataStrs[4]), float.Parse(dataStrs[5]));
  215. // }
  216. // }
  217. // if (MagCalibrationButton != null)
  218. // {
  219. // MagCalibrationButton.onClick.AddListener(delegate {
  220. // // if (MagCalibrater.Calibration)
  221. // if (MagCalibrater.Calibration)
  222. // {
  223. // Debug.Log(MagCalibrater.Calibration);
  224. // MagCalibrater.Calibration = false;
  225. // Debug.Log(MagCalibrater.Calibration);
  226. // MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  227. // float[] dataFloats = new float[6];
  228. // dataFloats[0] = MagCalibrater.Center.x;
  229. // dataFloats[1] = MagCalibrater.Center.y;
  230. // dataFloats[2] = MagCalibrater.Center.z;
  231. // dataFloats[3] = MagCalibrater.Radius.x;
  232. // dataFloats[4] = MagCalibrater.Radius.y;
  233. // dataFloats[5] = MagCalibrater.Radius.z;
  234. // string dataStr = String.Join(",", dataFloats);
  235. // PlayerPrefs.SetString("o0MagneticCalibrater", dataStr);
  236. // }
  237. // else
  238. // {
  239. // Debug.Log(MagCalibrater.Calibration);
  240. // MagCalibrater.Calibration = true;
  241. // Debug.Log(MagCalibrater.Calibration);
  242. // MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  243. // }
  244. // });
  245. // }
  246. try {
  247. string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  248. MagCalibrater = JsonConvert.DeserializeObject<o0MagneticCalibraterEllipsoidFitting>(magDataStr);
  249. //List<Vector3> list = MagCalibrater.getRecords();
  250. //this.ellipseScript.DrawPointCloud(list);
  251. //this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center);
  252. } catch(Exception) {
  253. MagCalibrater = null;
  254. }
  255. if (MagCalibrater == null)
  256. {
  257. MagCalibrater = new o0MagneticCalibraterEllipsoidFitting();
  258. }
  259. if (MagCalibrationButton != null)
  260. {
  261. MagCalibrationButton.onClick.AddListener(delegate {
  262. if (MagCalibrater.Calibration)
  263. {
  264. List<Vector3> list = MagCalibrater.getRecords();
  265. //停止校准时候,看看数组值
  266. float maxDistance = 0f,ratio = 1f;
  267. Vector3 maxVector3 = new Vector3(0,0,0);
  268. List<Vector3> endRecords = new List<Vector3>();
  269. foreach (Vector3 i in list)
  270. {
  271. Vector3 v = i - MagCalibrater._Center;
  272. if (Math.Abs(v.magnitude) > maxDistance)
  273. {
  274. maxVector3 = v;
  275. maxDistance = Math.Abs(v.magnitude);
  276. if(Math.Abs(v.magnitude) < Math.Abs(MagCalibrater._Radius.magnitude))
  277. ratio = Math.Abs(v.magnitude) / Math.Abs(MagCalibrater._Radius.magnitude);
  278. else
  279. ratio = Math.Abs(MagCalibrater._Radius.magnitude) / Math.Abs(v.magnitude);
  280. }
  281. }
  282. Debug.LogWarning(maxDistance + " == " + Math.Abs(MagCalibrater._Radius.magnitude) + " == " + MagCalibrater._Radius + " = " + maxVector3);
  283. //如果比例效果不理想。可以设置为ratio=0.5f
  284. foreach (Vector3 i in list)
  285. {
  286. //- MagCalibrater._Center
  287. Vector3 v = i ;
  288. v *= ratio;
  289. endRecords.Add(v);
  290. }
  291. this.ellipseScript.ClearAndUpdatePointArray();
  292. this.ellipseScript.DrawPointCloud(endRecords);
  293. //绘制椭圆形
  294. if (MagCalibrater._Radius != this.ellipseScript.ellipseTran.localScale)
  295. {
  296. this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center* ratio);
  297. //设置绘制图像相机的对应位置
  298. this.ellipseScript.setCameraPos(MagCalibrater._Center * 0.5f);
  299. }
  300. MagCalibrater.Calibration = false;
  301. MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  302. PlayerPrefs.SetString("o0MagneticCalibrater", JsonConvert.SerializeObject(MagCalibrater));
  303. }
  304. else
  305. {
  306. MagCalibrater.Calibration = true;
  307. MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  308. }
  309. });
  310. }
  311. try {
  312. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  313. GyrCalibrater = JsonConvert.DeserializeObject<o0GyrCalibrater>(gyrDataStr);
  314. if (GyrCalibrater._Average != Vector3.zero) GyrScaleText.text = "已校准";
  315. } catch(Exception) {
  316. GyrCalibrater = null;
  317. }
  318. if (GyrCalibrater == null)
  319. {
  320. GyrCalibrater = new o0GyrCalibrater();
  321. }
  322. if (GyrCalibrationButton != null)
  323. {
  324. GyrCalibrationButton.onClick.AddListener(delegate {
  325. if (GyrCalibrater.Calibration)
  326. {
  327. GyrCalibrater.Calibration = false;
  328. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  329. PlayerPrefs.SetString("o0GyrCalibrater", JsonConvert.SerializeObject(GyrCalibrater));
  330. }
  331. else
  332. {
  333. GyrCalibrater.Calibration = true;
  334. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  335. }
  336. });
  337. }
  338. }
  339. private void OnValueChanged(bool value)
  340. {
  341. if (value)
  342. {
  343. //选中了的逻辑
  344. }
  345. Debug.Log(value);
  346. }
  347. public void OnDataReceived(byte[] bytes)
  348. {
  349. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  350. if (bytes.Length != 26)
  351. {
  352. if (bytes[3] == 125)
  353. {
  354. DoIdentity();
  355. }
  356. return;
  357. }
  358. if (bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0)
  359. return;
  360. if (bytes[16] == 0 && bytes[17] == 0 && bytes[18] == 0 && bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0)
  361. return;
  362. float ax = -TwoByteToFloat(bytes[4], bytes[5]);
  363. float ay = TwoByteToFloat(bytes[6], bytes[7]);
  364. float az = -TwoByteToFloat(bytes[8], bytes[9]);
  365. ax = ax / 32768 * 16;
  366. ay = ay / 32768 * 16;
  367. az = az / 32768 * 16;
  368. Acc = new Vector3(ax, ay, az);
  369. float roll = TwoByteToFloat(bytes[10], bytes[11]);
  370. float pitch = TwoByteToFloat(bytes[12], bytes[13]);
  371. float yaw = TwoByteToFloat(bytes[14], bytes[15]);
  372. roll = -roll / 32768 * 2000;
  373. pitch = pitch / 32768 * 2000;
  374. yaw = -yaw / 32768 * 2000;
  375. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  376. Gyr = GyrCalibrater.Update(Gyr);
  377. if (GyrScaleText != null && GyrCalibrater.Calibration)
  378. {
  379. // GyrScaleText.text = GyrCalibrater._Average.x + "\n" + GyrCalibrater._Average.y + "\n" + GyrCalibrater._Average.z;
  380. // GyrScaleText.text = "Gyr*1000,000:" + (_9Axis.GyrOld * 1000000).ToString();
  381. GyrScaleText.text = "" + (_9Axis.GyrOld * 1000000).ToString();
  382. }
  383. float x = TwoByteToFloat(bytes[16], bytes[17]);
  384. float y = TwoByteToFloat(bytes[18], bytes[19]);
  385. float z = -TwoByteToFloat(bytes[20], bytes[21]);
  386. var mag = new Vector3(x, y, z);
  387. Mag = mag / 32768 * 256;
  388. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  389. {
  390. //绘制地磁计点
  391. if (MagCalibrater.Calibration)
  392. {
  393. this.ellipseScript.AddAndUpdatePointArray(Mag);
  394. }
  395. Mag = MagCalibrater.Update(Mag);
  396. if (MagScaleText != null)
  397. {
  398. MagScaleText.text = MagCalibrater._Radius.ToString();
  399. }
  400. }
  401. var ms = (((long)bytes[22]) *60 + bytes[23])*1000 + (long)TwoByteToFloat(bytes[1], bytes[2]);
  402. if(msOld == default)
  403. {
  404. msOld = ms;
  405. return;
  406. }
  407. TimeGap = ms - msOld;
  408. msOld = ms;
  409. newRotation = _9Axis.Update(Acc * 10, Gyr, Mag, TimeGap);
  410. // if(_9Axis.States.Count() < 10){
  411. // newRotation = _9Axis.States.Last().Qua;
  412. // }
  413. // else
  414. // {
  415. // int MuliteLerpCount = 10;
  416. // for (var i = 0;i< MuliteLerpCount;++i)
  417. // {
  418. // newRotation = Quaternion.Slerp(newRotation, _9Axis.States[_9Axis.States.Count() - MuliteLerpCount + i].Qua, 1/(i+1));
  419. // }
  420. // }
  421. receiveDataCount++;
  422. if (!hasAutoIdentity && receiveDataCount == 5) {
  423. doIdentity = true;
  424. }
  425. }
  426. void DoIdentity()
  427. {
  428. if (hasAutoIdentity)
  429. {
  430. doIdentity = true;
  431. Debug.Log("reset identity");
  432. }
  433. }
  434. public void Update()
  435. {
  436. if (hasAutoIdentity && controlObj != null)
  437. {
  438. // controlObj.localRotation = Quaternion.Lerp(controlObj.localRotation, newRotation, Time.deltaTime * 6);
  439. // controlObj.localRotation = newRotation;
  440. Quaternion nowRotation = controlObj.localRotation;
  441. filter.Update(ref nowRotation, newRotation);
  442. controlObj.localRotation = nowRotation;
  443. // GameObject.Find("Canvas/RPY_LOG").GetComponent<Text>().text =
  444. // "roll: " + controlObj.localEulerAngles.x +
  445. // "\npitch: " + controlObj.localEulerAngles.y +
  446. // "\nyaw: " + controlObj.localEulerAngles.z;
  447. GameObject.Find("Canvas/RPY_LOG").GetComponent<Text>().text =
  448. "x: " + _9Axis.States.Last().Qua.eulerAngles.x +
  449. "\ny: " + _9Axis.States.Last().Qua.eulerAngles.y +
  450. "\nz: " + _9Axis.States.Last().Qua.eulerAngles.z;
  451. }
  452. if (doIdentity)
  453. {
  454. _9Axis.SetIdentityAccordingToRecords();
  455. if (controlObj != null)
  456. {
  457. controlObj.localRotation = Quaternion.identity;
  458. }
  459. doIdentity = false;
  460. hasAutoIdentity = true;
  461. }
  462. }
  463. int receiveDataCount = 0;
  464. bool doIdentity = false;
  465. bool hasAutoIdentity = false;
  466. Quaternion newRotation;
  467. public void InitAutoIdentity()
  468. {
  469. receiveDataCount = 0;
  470. doIdentity = false;
  471. hasAutoIdentity = false;
  472. }
  473. }