BluetoothAim.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. using ArduinoBluetoothAPI;
  2. using System;
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using UnityEngine.UI;
  7. using o0Project;
  8. public class BluetoothAim : MonoBehaviour
  9. {
  10. BluetoothHelper bluetoothHelper;
  11. BluetoothHelperCharacteristic characteristicWrite;
  12. BluetoothHelperService bluetoothService;
  13. string deviceName = "";
  14. bool canConnect = true;
  15. [SerializeField] string targetDeviceName = "Bbow_20210501";
  16. [SerializeField] Text textUI;
  17. [SerializeField] Transform controlObj = default;
  18. [SerializeField] Button SetIdentity = default;
  19. [SerializeField] Button CalibrationButton = default;
  20. [SerializeField] Text MagScaleText = default;
  21. AimHandler aimHandler = null;
  22. public static bool scanLock = false; //防止同时扫描冲突
  23. void Start()
  24. {
  25. aimHandler = new AimHandler(controlObj, SetIdentity, CalibrationButton, MagScaleText);
  26. }
  27. void OnDestroy()
  28. {
  29. if (bluetoothHelper != null)
  30. {
  31. bluetoothHelper.Disconnect();
  32. }
  33. }
  34. void FixedUpdate()
  35. {
  36. Connect();
  37. }
  38. void Update()
  39. {
  40. aimHandler.Update();
  41. }
  42. void Connect()
  43. {
  44. if (BluetoothShoot.scanLock)
  45. {
  46. return;
  47. }
  48. if (!canConnect)
  49. {
  50. return;
  51. }
  52. scanLock = true;
  53. canConnect = false;
  54. try
  55. {
  56. BluetoothHelper.BLE = true;
  57. bluetoothHelper = BluetoothHelper.GetNewInstance();
  58. bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
  59. {
  60. Log("连接成功\n" + helper.getDeviceName());
  61. foreach (BluetoothHelperService service in helper.getGattServices())
  62. {
  63. if (service.getName().ToLower().StartsWith("0000fff0"))
  64. {
  65. bluetoothService = service;
  66. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  67. {
  68. if (characteristic.getName().ToLower().StartsWith("0000fff2"))
  69. {
  70. characteristicWrite = characteristic;
  71. }
  72. else if (characteristic.getName().ToLower().StartsWith("0000fff1"))
  73. {
  74. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  75. ch.setService(bluetoothService.getName());
  76. bluetoothHelper.Subscribe(ch);
  77. }
  78. }
  79. }
  80. }
  81. Invoke("OpenReceiveData", 1);
  82. Invoke("SetReceiveDataInterval20", 2);
  83. };
  84. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  85. {
  86. canConnect = true;
  87. Log("连接失败\n" + helper.getDeviceName());
  88. };
  89. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  90. {
  91. byte[] bytes = value;
  92. aimHandler.onDataReceived(bytes);
  93. };
  94. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  95. {
  96. scanLock = false;
  97. foreach (BluetoothDevice device in nearbyDevices)
  98. {
  99. if (device.DeviceName == targetDeviceName)
  100. {
  101. deviceName = device.DeviceName;
  102. bluetoothHelper.setDeviceName(deviceName);
  103. bluetoothHelper.Connect();
  104. Log("发现设备\n" + device.DeviceName);
  105. return;
  106. }
  107. }
  108. canConnect = true;
  109. Log("没有发现设备");
  110. };
  111. bluetoothHelper.ScanNearbyDevices();
  112. Log("正在扫描设备");
  113. }
  114. catch (Exception e)
  115. {
  116. Debug.Log(e.Message);
  117. canConnect = true;
  118. Log("请打开蓝牙");
  119. }
  120. }
  121. void OpenReceiveData()
  122. {
  123. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  124. ch.setService(bluetoothService.getName());
  125. bluetoothHelper.WriteCharacteristic(ch, "3");
  126. Log("开始接收信息\n" + deviceName);
  127. }
  128. void SetReceiveDataInterval20()
  129. {
  130. bluetoothHelper.WriteCharacteristic(characteristicWrite, "b");
  131. Log("修改接收频率\n" + deviceName);
  132. }
  133. void Log(string text)
  134. {
  135. if (textUI != null)
  136. {
  137. textUI.text = text;
  138. }
  139. }
  140. }
  141. class AimHandler
  142. {
  143. Transform controlObj;
  144. Button SetIdentity = default;
  145. Button CalibrationButton = default;
  146. Text MagScaleText = default;
  147. Vector3 Acc = default;
  148. Vector3 Gyr = default;
  149. Vector3 Mag = default;
  150. static Vector3 AccIdentity = new Vector3(0, -1, 0);
  151. static Vector3 MagIdentity = new Vector3(-1, 2, 0).normalized;
  152. public class State
  153. {
  154. public long TimeGap;
  155. public Vector3 Acc = AccIdentity;
  156. public Vector3 Gyr;
  157. public Vector3 Mag = MagIdentity;
  158. public Quaternion Qua;
  159. public float Variance = 1;
  160. }
  161. List<State> States = new List<State>();
  162. Vector3 AccOld;
  163. Vector3 GyrOld;
  164. Vector3 MagOld;
  165. long TimeGapOld;
  166. Quaternion o06DOFUpdate(Vector3 AccOld, Vector3 GyrOld, Vector3 MagOld, long TimeGapOld)
  167. {
  168. var Acc = this.AccOld;
  169. var Gyr = this.GyrOld;
  170. var Mag = this.MagOld;
  171. float TimeGap = (TimeGapOld + this.TimeGapOld) / 2;
  172. this.AccOld = AccOld;
  173. this.GyrOld = GyrOld;
  174. this.MagOld = MagOld;
  175. this.TimeGapOld = TimeGapOld;
  176. var Last = States.LastOrDefault() ?? new State();
  177. States.Add(new State());
  178. if (States.Count > 10)
  179. States.RemoveAt(0);
  180. var state = States.Last();
  181. state.Acc = Acc;
  182. state.Gyr = Gyr;
  183. state.Mag = Mag;
  184. var LastQuaternion = Last.Qua;
  185. var newQua = new Quaternion();
  186. newQua.eulerAngles = Gyr * TimeGap;
  187. var quaGyr = LastQuaternion * newQua;
  188. float AccLengthToAngle = 90;//1倍引力差相当于多少度方差
  189. float MagLengthToAngle = 90;//1倍磁力差相当于多少度方差
  190. float GyrVariance = state.Variance + TimeGap/100 + (Gyr * TimeGap).magnitude * 0.02f;
  191. float AccVariance = TimeGap / 5 + Mathf.Sqrt(Mathf.Pow((Acc.magnitude - 9.8f) / 9.8f * AccLengthToAngle, 2)+ Mathf.Pow(Vector3.Angle(Acc,Last.Acc) * 0.5f, 2));
  192. float MagVariance = TimeGap / 5 + Mathf.Sqrt(Mathf.Pow((Mag.magnitude - 1) / 1 * MagLengthToAngle, 2) + Mathf.Pow(Vector3.Angle(Mag, Last.Mag) * 0.1f, 2));
  193. state.Variance = state.Variance * AccVariance / (state.Variance + AccVariance);
  194. state.Variance = state.Variance * MagVariance / (state.Variance + MagVariance);
  195. var quaAccMag = o0Project.o0.FormQuaternion(AccIdentity, MagIdentity, Acc, Mag, AccVariance / (AccVariance + MagVariance));
  196. var quaMinRate = GyrVariance / (GyrVariance + Mathf.Max(AccVariance, MagVariance));
  197. var quaMaxRate = GyrVariance / (GyrVariance + Mathf.Min(AccVariance, MagVariance));
  198. Quaternion quaFirst = Quaternion.Slerp(quaGyr, quaAccMag, quaMinRate).normalized;
  199. float quaSecondRate = (quaMaxRate - quaMinRate) / (1 - quaMinRate);
  200. state.Qua = AccVariance < MagVariance ? o0Project.o0.FormQuaternion(quaFirst, AccIdentity, Acc, quaSecondRate): o0Project.o0.FormQuaternion(quaFirst, MagIdentity, Mag, quaSecondRate);
  201. return state.Qua;
  202. }
  203. //转换读取的数据,无符号->有符号
  204. float TwoByteToFloat(byte b1, byte b2)
  205. {
  206. ushort twoByte = (ushort) (b1 * 256 + b2);
  207. short shortNum = (short) twoByte;
  208. return (float) shortNum;
  209. }
  210. o0MagneticCalibrater MagCalibrater;
  211. o0Vector3Filter MagFilter = new o0Vector3Filter();
  212. long msOld = 0;
  213. public AimHandler(Transform controlObj, Button SetIdentity, Button CalibrationButton, Text MagScaleText)
  214. {
  215. this.controlObj = controlObj;
  216. this.SetIdentity = SetIdentity;
  217. this.CalibrationButton = CalibrationButton;
  218. this.MagScaleText = MagScaleText;
  219. SetIdentity.onClick.AddListener(DoIdentity);
  220. MagCalibrater = new o0MagneticCalibrater();
  221. string caliraterDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  222. if (caliraterDataStr.Length > 0)
  223. {
  224. string[] dataStrs = caliraterDataStr.Split(',');
  225. if (dataStrs.Length == 6)
  226. {
  227. MagCalibrater._Center = new Vector3(float.Parse(dataStrs[0]), float.Parse(dataStrs[1]), float.Parse(dataStrs[2]));
  228. MagCalibrater._Radius = new Vector3(float.Parse(dataStrs[3]), float.Parse(dataStrs[4]), float.Parse(dataStrs[5]));
  229. }
  230. }
  231. CalibrationButton.onClick.AddListener(delegate {
  232. if (MagCalibrater.Calibration)
  233. {
  234. MagCalibrater.Calibration = false;
  235. CalibrationButton.GetComponentInChildren<Text>().text = "开始磁场校准";
  236. float[] dataFloats = new float[6];
  237. dataFloats[0] = MagCalibrater.Center.x;
  238. dataFloats[1] = MagCalibrater.Center.y;
  239. dataFloats[2] = MagCalibrater.Center.z;
  240. dataFloats[3] = MagCalibrater.Radius.x;
  241. dataFloats[4] = MagCalibrater.Radius.y;
  242. dataFloats[5] = MagCalibrater.Radius.z;
  243. string dataStr = String.Join(",", dataFloats);
  244. PlayerPrefs.SetString("o0MagneticCalibrater", dataStr);
  245. }
  246. else
  247. {
  248. MagCalibrater.Calibration = true;
  249. CalibrationButton.GetComponentInChildren<Text>().text = "停止磁场校准";
  250. }
  251. });
  252. }
  253. public void onDataReceived(byte[] bytes)
  254. {
  255. if (bytes.Length != 26)
  256. {
  257. if (bytes[3] == 125)
  258. {
  259. DoIdentity();
  260. }
  261. return;
  262. }
  263. if (bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0)
  264. return;
  265. if (bytes[16] == 0 && bytes[17] == 0 && bytes[18] == 0 && bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0)
  266. return;
  267. float ax = -TwoByteToFloat(bytes[4], bytes[5]);
  268. float ay = TwoByteToFloat(bytes[6], bytes[7]);
  269. float az = -TwoByteToFloat(bytes[8], bytes[9]);
  270. ax = ax / 32768 * 16;
  271. ay = ay / 32768 * 16;
  272. az = az / 32768 * 16;/**/
  273. Acc = new Vector3(ax, ay, az);
  274. float roll = TwoByteToFloat(bytes[10], bytes[11]);
  275. float pitch = TwoByteToFloat(bytes[12], bytes[13]);
  276. float yaw = TwoByteToFloat(bytes[14], bytes[15]);
  277. roll = -roll / 32768 * 2000;
  278. pitch = pitch / 32768 * 2000;
  279. yaw = -yaw / 32768 * 2000;
  280. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  281. var gyr = new Vector3(roll, pitch, yaw) / 1000 * 20;// timeGap;
  282. float x = TwoByteToFloat(bytes[16], bytes[17]);
  283. float y = TwoByteToFloat(bytes[18], bytes[19]);
  284. float z = -TwoByteToFloat(bytes[20], bytes[21]);/**/
  285. var mag = new Vector3(x, y, z);
  286. Mag = mag / 32768 * 256;
  287. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  288. {
  289. Mag = MagCalibrater.Update(Mag);
  290. MagScaleText.text = MagCalibrater._Radius.ToString() + MagCalibrater.CalibratCompletionPercentage() + "%";
  291. }
  292. var ms = (((long)bytes[22]) *60 + bytes[23])*1000 + (long)TwoByteToFloat(bytes[1], bytes[2]);
  293. if(msOld == default)
  294. {
  295. msOld = ms;
  296. return;
  297. }
  298. var TimeGap = ms - msOld;
  299. msOld = ms;
  300. newRotation = o06DOFUpdate(Acc * 10, Gyr, Mag, TimeGap);
  301. receiveDataCount++;
  302. if (!hasAutoIdentity && receiveDataCount == 5) {
  303. doIdentity = true;
  304. }
  305. }
  306. void DoIdentity()
  307. {
  308. if (hasAutoIdentity)
  309. {
  310. doIdentity = true;
  311. Debug.Log("reset identity");
  312. }
  313. }
  314. public void Update()
  315. {
  316. if (hasAutoIdentity)
  317. {
  318. controlObj.transform.localRotation = Quaternion.Lerp(controlObj.transform.localRotation, newRotation, Time.deltaTime * 6);
  319. // newEularAngles.x = baseEularAngles.x + newRotation.eulerAngles.x;
  320. // newEularAngles.y = baseEularAngles.y + newRotation.eulerAngles.y;
  321. // newEularAngles.z = baseEularAngles.z + newRotation.eulerAngles.z;
  322. // controlObj.transform.localRotation = Quaternion.Lerp(
  323. // controlObj.transform.localRotation,
  324. // Quaternion.Euler(newEularAngles.x, newEularAngles.y, newEularAngles.z),
  325. // Time.deltaTime * 8
  326. // );
  327. // controlObj.localEulerAngles = Vector3.Lerp(controlObj.localEulerAngles, newEularAngles, Time.deltaTime * 6);
  328. }
  329. if (doIdentity)
  330. {
  331. if (Quaternion.Angle(newRotation, baseRotation) < 2)
  332. {
  333. if (!hasAutoIdentity)
  334. {
  335. controlObj.transform.localRotation = newRotation;
  336. }
  337. doIdentity = false;
  338. hasAutoIdentity = true;
  339. } else {
  340. AccIdentity = AccOld;
  341. MagIdentity = MagOld;
  342. }
  343. // baseEularAngles.x = 0 - newRotation.eulerAngles.x;
  344. // baseEularAngles.y = 0 - newRotation.eulerAngles.y;
  345. // baseEularAngles.z = 0 - newRotation.eulerAngles.z;
  346. // newEularAngles.x = baseEularAngles.x + newRotation.eulerAngles.x;
  347. // newEularAngles.y = baseEularAngles.y + newRotation.eulerAngles.y;
  348. // newEularAngles.z = baseEularAngles.z + newRotation.eulerAngles.z;
  349. // controlObj.localEulerAngles = newEularAngles;
  350. // doIdentity = false;
  351. // hasAutoIdentity = true;
  352. }
  353. }
  354. int receiveDataCount = 0;
  355. bool doIdentity = false;
  356. bool hasAutoIdentity = false;
  357. Quaternion newRotation;
  358. Quaternion baseRotation = new Quaternion(0, 0, 0, 1);
  359. Vector3 baseEularAngles = new Vector3();
  360. Vector3 newEularAngles = new Vector3();
  361. }