BluetoothAim.cs 13 KB

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