BluetoothAim.cs 18 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] 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 < 9; ++i)
  216. {
  217. _9Axis.Tester.Add(GameObject.Find("Canvas").transform.Find("DrawImage").Find(i.ToString()).gameObject.AddComponent<o0UIRawImageTester>());
  218. }
  219. for (var i = 0; i < 15; ++i)
  220. {
  221. _9Axis.TextTester.Add(GameObject.Find("Canvas").transform.Find("DebugTexts").transform.Find("Text" + i.ToString()).gameObject.GetComponent<Text>());
  222. }
  223. if (SetIdentity != null)
  224. {
  225. SetIdentity.onClick.AddListener(DoIdentity);
  226. }
  227. try
  228. {
  229. string magDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  230. MagCalibrater = JsonConvert.DeserializeObject<o0MagneticCalibraterEllipsoidFitting>(magDataStr);
  231. }
  232. catch(Exception)
  233. {
  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. List<Vector3> list = MagCalibrater.getRecords();
  246. //停止校准时候,看看数组值
  247. float maxDistance = 0f,ratio = 1f;
  248. Vector3 maxVector3 = new Vector3(0,0,0);
  249. List<Vector3> endRecords = new List<Vector3>();
  250. foreach (Vector3 i in list)
  251. {
  252. Vector3 v = i - MagCalibrater._Center;
  253. if (Math.Abs(v.magnitude) > maxDistance)
  254. {
  255. maxVector3 = v;
  256. maxDistance = Math.Abs(v.magnitude);
  257. if(Math.Abs(v.magnitude) < Math.Abs(MagCalibrater._Radius.magnitude))
  258. ratio = Math.Abs(v.magnitude) / Math.Abs(MagCalibrater._Radius.magnitude);
  259. else
  260. ratio = Math.Abs(MagCalibrater._Radius.magnitude) / Math.Abs(v.magnitude);
  261. }
  262. }
  263. Debug.LogWarning(maxDistance + " == " + Math.Abs(MagCalibrater._Radius.magnitude) + " == " + MagCalibrater._Radius + " = " + maxVector3);
  264. //如果比例效果不理想。可以设置为ratio=0.5f
  265. foreach (Vector3 i in list)
  266. {
  267. //- MagCalibrater._Center
  268. Vector3 v = i ;
  269. v *= ratio;
  270. if(endRecords.Count>3000)
  271. {
  272. endRecords.RemoveAt(0);
  273. }
  274. endRecords.Add(v);
  275. }
  276. this.ellipseScript.ClearAndUpdatePointArray();
  277. this.ellipseScript.DrawPointCloud(endRecords);
  278. //绘制椭圆形
  279. if (MagCalibrater._Radius != this.ellipseScript.ellipseTran.localScale)
  280. {
  281. this.ellipseScript.setEllipseLocalScaleAndCenter(MagCalibrater._Radius, MagCalibrater._Center* ratio);
  282. //设置绘制图像相机的对应位置
  283. this.ellipseScript.setCameraPos(MagCalibrater._Center * 0.5f);
  284. }
  285. MagCalibrater.Calibration = false;
  286. MagCalibrationButton.GetComponentInChildren<Text>().text = "开始地磁计校准";
  287. PlayerPrefs.SetString("o0MagneticCalibrater", JsonConvert.SerializeObject(MagCalibrater));
  288. }
  289. else
  290. {
  291. MagCalibrater.Calibration = true;
  292. MagCalibrationButton.GetComponentInChildren<Text>().text = "停止地磁计校准";
  293. this.cMaxVector = new Vector3(0, 0, 0);
  294. this.cMinVector = new Vector3(0, 0, 0);
  295. }
  296. });
  297. }
  298. try {
  299. string gyrDataStr = PlayerPrefs.GetString("o0GyrCalibrater");
  300. GyrCalibrater = JsonConvert.DeserializeObject<o0GyrCalibrater>(gyrDataStr);
  301. if (GyrCalibrater._Average != Vector3.zero) GyrScaleText.text = "已校准";
  302. } catch(Exception) {
  303. GyrCalibrater = null;
  304. }
  305. if (GyrCalibrater == null)
  306. {
  307. GyrCalibrater = new o0GyrCalibrater();
  308. }
  309. if (GyrCalibrationButton != null)
  310. {
  311. GyrCalibrationButton.onClick.AddListener(delegate {
  312. if (GyrCalibrater.Calibration)
  313. {
  314. GyrCalibrater.Calibration = false;
  315. GyrCalibrationButton.GetComponentInChildren<Text>().text = "开始陀螺仪校准";
  316. PlayerPrefs.SetString("o0GyrCalibrater", JsonConvert.SerializeObject(GyrCalibrater));
  317. }
  318. else
  319. {
  320. GyrCalibrater.Calibration = true;
  321. GyrCalibrationButton.GetComponentInChildren<Text>().text = "停止陀螺仪校准";
  322. }
  323. });
  324. }
  325. }
  326. private void OnValueChanged(bool value)
  327. {
  328. if (value)
  329. {
  330. //选中了的逻辑
  331. }
  332. Debug.Log(value);
  333. }
  334. GameObject AccObj = GameObject.Find("Acc");
  335. GameObject MagObj = GameObject.Find("Mag");
  336. GameObject AMesh = GameObject.Find("AMesh");
  337. public void OnDataReceived(byte[] bytes)
  338. {
  339. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  340. if (bytes.Length != 26)
  341. {
  342. if (bytes[3] == 125)
  343. {
  344. DoIdentity();
  345. }
  346. return;
  347. }
  348. if (bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0)
  349. return;
  350. if (bytes[16] == 0 && bytes[17] == 0 && bytes[18] == 0 && bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0)
  351. return;
  352. float ax = -TwoByteToFloat(bytes[4], bytes[5]);
  353. float ay = TwoByteToFloat(bytes[6], bytes[7]);
  354. float az = -TwoByteToFloat(bytes[8], bytes[9]);
  355. ax = ax / 32768 * 16;
  356. ay = ay / 32768 * 16;
  357. az = az / 32768 * 16;
  358. Acc = new Vector3(ax, ay, az);
  359. AccObj.transform.GetChild(0).localPosition = Acc;
  360. float roll = TwoByteToFloat(bytes[10], bytes[11]);
  361. float pitch = TwoByteToFloat(bytes[12], bytes[13]);
  362. float yaw = TwoByteToFloat(bytes[14], bytes[15]);
  363. roll = -roll / 32768 * 2000;
  364. pitch = pitch / 32768 * 2000;
  365. yaw = -yaw / 32768 * 2000;
  366. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  367. Gyr = GyrCalibrater.Update(Gyr);
  368. if (GyrScaleText != null && GyrCalibrater.Calibration)
  369. {
  370. // GyrScaleText.text = GyrCalibrater._Average.x + "\n" + GyrCalibrater._Average.y + "\n" + GyrCalibrater._Average.z;
  371. // GyrScaleText.text = "Gyr*1000,000:" + (_9Axis.GyrOld * 1000000).ToString();
  372. GyrScaleText.text = "" + (_9Axis.GyrOld * 1000000).ToString();
  373. }
  374. float x = TwoByteToFloat(bytes[16], bytes[17]);
  375. float y = TwoByteToFloat(bytes[18], bytes[19]);
  376. float z = -TwoByteToFloat(bytes[20], bytes[21]);
  377. var mag = new Vector3(x, y, z);
  378. Mag = mag / 32768 * 256;
  379. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  380. {
  381. //绘制地磁计点
  382. if (MagCalibrater.Calibration)
  383. {
  384. this.ellipseScript.AddAndUpdatePointArray(Mag);
  385. if (Mag.magnitude > this.cMaxVector.magnitude)
  386. {
  387. this.cMaxVector = Mag;
  388. }
  389. else if (Mag.magnitude < this.cMinVector.magnitude) {
  390. this.cMinVector = Mag;
  391. }
  392. Vector3 _center = this.cMaxVector - this.cMinVector;
  393. Debug.LogWarning(_center + " == "+ _center.magnitude);
  394. //设置绘制图像相机的对应位置
  395. this.ellipseScript.setCameraPos(_center/2);
  396. }
  397. Mag = MagCalibrater.Update(Mag);
  398. if (MagScaleText != null)
  399. {
  400. MagScaleText.text = MagCalibrater._Radius.ToString();
  401. }
  402. }
  403. MagObj.transform.GetChild(0).localPosition = Mag;
  404. var ms = (((long)bytes[22]) *60 + bytes[23])*1000 + (long)TwoByteToFloat(bytes[1], bytes[2]);
  405. if(msOld == default)
  406. {
  407. msOld = ms;
  408. return;
  409. }
  410. TimeGap = ms - msOld;
  411. msOld = ms;
  412. AMesh.transform.localRotation = newRotation = _9Axis.Update(Acc * 10, Gyr, Mag, TimeGap);
  413. receiveDataCount++;
  414. if (!hasAutoIdentity && receiveDataCount == 5) {
  415. doIdentity = true;
  416. }
  417. }
  418. void DoIdentity()
  419. {
  420. if (hasAutoIdentity)
  421. {
  422. doIdentity = true;
  423. Debug.Log("reset identity");
  424. }
  425. }
  426. public void Update()
  427. {
  428. if (hasAutoIdentity && controlObj != null)
  429. {
  430. Quaternion nowRotation = controlObj.localRotation;
  431. filter.Update(ref nowRotation, newRotation);
  432. controlObj.localRotation = nowRotation;
  433. // GameObject.Find("Canvas/RPY_LOG").GetComponent<Text>().text =
  434. // "roll: " + controlObj.localEulerAngles.x +
  435. // "\npitch: " + controlObj.localEulerAngles.y +
  436. // "\nyaw: " + controlObj.localEulerAngles.z;
  437. // GameObject.Find("Canvas/RPY_LOG").GetComponent<Text>().text =
  438. // "x: " + _9Axis.x +
  439. // "\ny: " + _9Axis.y +
  440. // "\nz: " + _9Axis.States.z;
  441. }
  442. if (doIdentity)
  443. {
  444. // _9Axis.SetIdentityAccordingToRecords();
  445. _9Axis.SetIdentity();
  446. if (controlObj != null)
  447. {
  448. controlObj.localRotation = _9Axis.States.Last().Qua;
  449. }
  450. doIdentity = false;
  451. hasAutoIdentity = true;
  452. }
  453. }
  454. int receiveDataCount = 0;
  455. bool doIdentity = false;
  456. bool hasAutoIdentity = false;
  457. Quaternion newRotation;
  458. public void InitAutoIdentity()
  459. {
  460. receiveDataCount = 0;
  461. doIdentity = false;
  462. hasAutoIdentity = false;
  463. }
  464. }