BluetoothAim.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. using ArduinoBluetoothAPI;
  2. using System;
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using UnityEngine.UI;
  7. public class BluetoothAim : MonoBehaviour
  8. {
  9. BluetoothHelper bluetoothHelper;
  10. BluetoothHelperCharacteristic characteristicWrite;
  11. BluetoothHelperService bluetoothService;
  12. string deviceName = "";
  13. bool canConnect = true;
  14. [SerializeField] string targetDeviceName = "Bbow_20210501";
  15. [SerializeField] Text textUI;
  16. [SerializeField] Transform controlObj = default;
  17. [SerializeField] Button SetIdentity = default;
  18. [SerializeField] Button CalibrationButton = default;
  19. [SerializeField] Text MagScaleText = default;
  20. AimHandler aimHandler = null;
  21. public static bool scanLock = false; //防止同时扫描冲突
  22. void Start()
  23. {
  24. aimHandler = new AimHandler(controlObj, SetIdentity, CalibrationButton, MagScaleText);
  25. BluetoothDispatcher.aim = aimHandler.OnDataReceived;
  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. };
  83. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  84. {
  85. canConnect = true;
  86. Log("连接失败\n" + helper.getDeviceName());
  87. };
  88. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  89. {
  90. byte[] bytes = value;
  91. BluetoothClient.UploadData(0, bytes);
  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 Log(string text)
  129. {
  130. if (textUI != null)
  131. {
  132. textUI.text = text;
  133. }
  134. }
  135. }
  136. class AimHandler
  137. {
  138. Transform controlObj;
  139. Button SetIdentity = default;
  140. Button CalibrationButton = default;
  141. Text MagScaleText = default;
  142. Vector3 Acc = default;
  143. Vector3 Gyr = default;
  144. Vector3 Mag = default;
  145. long TimeGap = default;
  146. static Vector3 AccIdentity = new Vector3(0, -1, 0);
  147. static Vector3 MagIdentity = new Vector3(-1, 2, 0).normalized;
  148. public class State
  149. {
  150. public long TimeGap;
  151. public Vector3 Acc = AccIdentity;
  152. public Vector3 Gyr;
  153. public Vector3 Mag = MagIdentity;
  154. public Quaternion Qua;
  155. public float Variance = 1;
  156. }
  157. List<State> States = new List<State>();
  158. Vector3 AccOld;
  159. Vector3 GyrOld;
  160. Vector3 MagOld;
  161. long TimeGapOld;
  162. Quaternion o06DOFUpdate(Vector3 AccOld, Vector3 GyrOld, Vector3 MagOld, long TimeGapOld)
  163. {
  164. var Acc = this.AccOld;
  165. var Gyr = this.GyrOld;
  166. var Mag = this.MagOld;
  167. float TimeGap = (TimeGapOld + this.TimeGapOld) / 2;
  168. this.AccOld = AccOld;
  169. this.GyrOld = GyrOld;
  170. this.MagOld = MagOld;
  171. this.TimeGapOld = TimeGapOld;
  172. var Last = States.LastOrDefault() ?? new State();
  173. States.Add(new State());
  174. if (States.Count > 10)
  175. States.RemoveAt(0);
  176. var state = States.Last();
  177. state.Acc = Acc;
  178. state.Gyr = Gyr;
  179. state.Mag = Mag;
  180. var LastQuaternion = Last.Qua;
  181. var newQua = new Quaternion();
  182. newQua.eulerAngles = Gyr * TimeGap;
  183. var quaGyr = LastQuaternion * newQua;
  184. float AccLengthToAngle = 90;//1倍引力差相当于多少度方差
  185. float MagLengthToAngle = 90;//1倍磁力差相当于多少度方差
  186. float GyrVariance = state.Variance + TimeGap/100 + (Gyr * TimeGap).magnitude * 0.02f;
  187. 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));
  188. float MagVariance = TimeGap / 5 + Mathf.Sqrt(Mathf.Pow((Mag.magnitude - 1) / 1 * MagLengthToAngle, 2) + Mathf.Pow(Vector3.Angle(Mag, Last.Mag) * 0.1f, 2));
  189. state.Variance = state.Variance * AccVariance / (state.Variance + AccVariance);
  190. state.Variance = state.Variance * MagVariance / (state.Variance + MagVariance);
  191. var quaAccMag = o0Project.o0.FormQuaternion(AccIdentity, MagIdentity, Acc, Mag, AccVariance / (AccVariance + MagVariance));
  192. var quaMinRate = GyrVariance / (GyrVariance + Mathf.Max(AccVariance, MagVariance));
  193. var quaMaxRate = GyrVariance / (GyrVariance + Mathf.Min(AccVariance, MagVariance));
  194. Quaternion quaFirst = Quaternion.Slerp(quaGyr, quaAccMag, quaMinRate).normalized;
  195. float quaSecondRate = (quaMaxRate - quaMinRate) / (1 - quaMinRate);
  196. state.Qua = AccVariance < MagVariance ? o0Project.o0.FormQuaternion(quaFirst, AccIdentity, Acc, quaSecondRate): o0Project.o0.FormQuaternion(quaFirst, MagIdentity, Mag, quaSecondRate);
  197. return state.Qua;
  198. }
  199. //转换读取的数据,无符号->有符号
  200. float TwoByteToFloat(byte b1, byte b2)
  201. {
  202. ushort twoByte = (ushort) (b1 * 256 + b2);
  203. short shortNum = (short) twoByte;
  204. return (float) shortNum;
  205. }
  206. o0MagneticCalibrater MagCalibrater;
  207. o0Vector3Filter MagFilter = new o0Vector3Filter();
  208. long msOld = 0;
  209. public AimHandler(Transform controlObj, Button SetIdentity, Button CalibrationButton, Text MagScaleText)
  210. {
  211. this.controlObj = controlObj;
  212. this.SetIdentity = SetIdentity;
  213. this.CalibrationButton = CalibrationButton;
  214. this.MagScaleText = MagScaleText;
  215. SetIdentity.onClick.AddListener(DoIdentity);
  216. MagCalibrater = new o0MagneticCalibrater();
  217. string caliraterDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  218. if (caliraterDataStr.Length > 0)
  219. {
  220. string[] dataStrs = caliraterDataStr.Split(',');
  221. if (dataStrs.Length == 6)
  222. {
  223. MagCalibrater._Center = new Vector3(float.Parse(dataStrs[0]), float.Parse(dataStrs[1]), float.Parse(dataStrs[2]));
  224. MagCalibrater._Radius = new Vector3(float.Parse(dataStrs[3]), float.Parse(dataStrs[4]), float.Parse(dataStrs[5]));
  225. }
  226. }
  227. CalibrationButton.onClick.AddListener(delegate {
  228. if (MagCalibrater.Calibration)
  229. {
  230. MagCalibrater.Calibration = false;
  231. CalibrationButton.GetComponentInChildren<Text>().text = "开始磁场校准";
  232. float[] dataFloats = new float[6];
  233. dataFloats[0] = MagCalibrater.Center.x;
  234. dataFloats[1] = MagCalibrater.Center.y;
  235. dataFloats[2] = MagCalibrater.Center.z;
  236. dataFloats[3] = MagCalibrater.Radius.x;
  237. dataFloats[4] = MagCalibrater.Radius.y;
  238. dataFloats[5] = MagCalibrater.Radius.z;
  239. string dataStr = String.Join(",", dataFloats);
  240. PlayerPrefs.SetString("o0MagneticCalibrater", dataStr);
  241. }
  242. else
  243. {
  244. MagCalibrater.Calibration = true;
  245. CalibrationButton.GetComponentInChildren<Text>().text = "停止磁场校准";
  246. }
  247. });
  248. }
  249. public void OnDataReceived(byte[] bytes)
  250. {
  251. if (bytes.Length != 26)
  252. {
  253. if (bytes[3] == 125)
  254. {
  255. DoIdentity();
  256. }
  257. return;
  258. }
  259. if (bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0)
  260. return;
  261. if (bytes[16] == 0 && bytes[17] == 0 && bytes[18] == 0 && bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0)
  262. return;
  263. float ax = -TwoByteToFloat(bytes[4], bytes[5]);
  264. float ay = TwoByteToFloat(bytes[6], bytes[7]);
  265. float az = -TwoByteToFloat(bytes[8], bytes[9]);
  266. ax = ax / 32768 * 16;
  267. ay = ay / 32768 * 16;
  268. az = az / 32768 * 16;/**/
  269. Acc = new Vector3(ax, ay, az);
  270. float roll = TwoByteToFloat(bytes[10], bytes[11]);
  271. float pitch = TwoByteToFloat(bytes[12], bytes[13]);
  272. float yaw = TwoByteToFloat(bytes[14], bytes[15]);
  273. roll = -roll / 32768 * 2000;
  274. pitch = pitch / 32768 * 2000;
  275. yaw = -yaw / 32768 * 2000;
  276. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  277. var gyr = new Vector3(roll, pitch, yaw) / 1000 * 20;// timeGap;
  278. float x = TwoByteToFloat(bytes[16], bytes[17]);
  279. float y = TwoByteToFloat(bytes[18], bytes[19]);
  280. float z = -TwoByteToFloat(bytes[20], bytes[21]);/**/
  281. var mag = new Vector3(x, y, z);
  282. Mag = mag / 32768 * 256;
  283. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  284. {
  285. Mag = MagCalibrater.Update(Mag);
  286. MagScaleText.text = MagCalibrater._Radius.ToString() + MagCalibrater.CalibratCompletionPercentage() + "%";
  287. }
  288. var ms = (((long)bytes[22]) *60 + bytes[23])*1000 + (long)TwoByteToFloat(bytes[1], bytes[2]);
  289. if(msOld == default)
  290. {
  291. msOld = ms;
  292. return;
  293. }
  294. TimeGap = ms - msOld;
  295. msOld = ms;
  296. newRotation = o06DOFUpdate(Acc * 10, Gyr, Mag, TimeGap);
  297. receiveDataCount++;
  298. if (!hasAutoIdentity && receiveDataCount == 5) {
  299. doIdentity = true;
  300. }
  301. }
  302. void DoIdentity()
  303. {
  304. if (hasAutoIdentity)
  305. {
  306. doIdentity = true;
  307. Debug.Log("reset identity");
  308. }
  309. }
  310. public void Update()
  311. {
  312. if (hasAutoIdentity)
  313. {
  314. controlObj.transform.localRotation = Quaternion.Lerp(controlObj.transform.localRotation, newRotation, Time.deltaTime * 6);
  315. }
  316. if (doIdentity)
  317. {
  318. if (Quaternion.Angle(newRotation, baseRotation) < 2)
  319. {
  320. if (!hasAutoIdentity)
  321. {
  322. controlObj.transform.localRotation = newRotation;
  323. }
  324. doIdentity = false;
  325. hasAutoIdentity = true;
  326. } else {
  327. AccIdentity = AccOld;
  328. MagIdentity = MagOld;
  329. }
  330. }
  331. }
  332. int receiveDataCount = 0;
  333. bool doIdentity = false;
  334. bool hasAutoIdentity = false;
  335. Quaternion newRotation;
  336. Quaternion baseRotation = new Quaternion(0, 0, 0, 1);
  337. }