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. 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. // Log(String.Join(",", bytes));
  92. BluetoothClient.UploadData(0, bytes);
  93. aimHandler.OnDataReceived(bytes);
  94. };
  95. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  96. {
  97. scanLock = false;
  98. foreach (BluetoothDevice device in nearbyDevices)
  99. {
  100. if (device.DeviceName == targetDeviceName)
  101. {
  102. deviceName = device.DeviceName;
  103. bluetoothHelper.setDeviceName(deviceName);
  104. bluetoothHelper.Connect();
  105. Log("发现设备\n" + device.DeviceName);
  106. return;
  107. }
  108. }
  109. canConnect = true;
  110. Log("没有发现设备");
  111. };
  112. bluetoothHelper.ScanNearbyDevices();
  113. Log("正在扫描设备");
  114. }
  115. catch (Exception e)
  116. {
  117. Debug.Log(e.Message);
  118. canConnect = true;
  119. Log("请打开蓝牙");
  120. }
  121. }
  122. void OpenReceiveData()
  123. {
  124. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  125. ch.setService(bluetoothService.getName());
  126. bluetoothHelper.WriteCharacteristic(ch, "3");
  127. Log("瞄准模块准备完成\n" + deviceName);
  128. }
  129. void Log(string text)
  130. {
  131. if (textUI != null)
  132. {
  133. textUI.text = text;
  134. }
  135. }
  136. public void SetControlObject(Transform obj)
  137. {
  138. this.aimHandler.controlObj = obj;
  139. if (obj != null)
  140. {
  141. this.aimHandler.InitAutoIdentity();
  142. }
  143. }
  144. }
  145. class AimHandler
  146. {
  147. public Transform controlObj;
  148. Button SetIdentity = default;
  149. Button CalibrationButton = default;
  150. Text MagScaleText = default;
  151. long TimeGap = default;
  152. Vector3 Acc = default;
  153. Vector3 Gyr = default;
  154. Vector3 Mag = default;
  155. static Vector3 AccIdentity = new Vector3(0, -1, 0);
  156. static Vector3 MagIdentity = new Vector3(-1, 2, 0).normalized;
  157. public class State
  158. {
  159. public long TimeGap;
  160. public Vector3 Acc = AccIdentity;
  161. public Vector3 Gyr;
  162. public Vector3 Mag = MagIdentity;
  163. public Quaternion Qua;
  164. public float Variance = 1;
  165. }
  166. List<State> States = new List<State>();
  167. long TimeGapOld;
  168. Vector3 AccOld;
  169. Vector3 GyrOld;
  170. Vector3 MagOld;
  171. Quaternion o06DOFUpdate(Vector3 AccOld, Vector3 GyrOld, Vector3 MagOld, long TimeGapOld)
  172. {
  173. var Acc = this.AccOld;
  174. var Gyr = this.GyrOld;
  175. var Mag = this.MagOld;
  176. float TimeGap = (TimeGapOld + this.TimeGapOld) / 2;
  177. this.AccOld = AccOld;
  178. this.GyrOld = GyrOld;
  179. this.MagOld = MagOld;
  180. this.TimeGapOld = TimeGapOld;
  181. var Last = States.LastOrDefault() ?? new State();
  182. States.Add(new State());
  183. if (States.Count > 10)
  184. States.RemoveAt(0);
  185. var state = States.Last();
  186. state.Acc = Acc;
  187. state.Gyr = Gyr;
  188. state.Mag = Mag;
  189. var LastQuaternion = Last.Qua;
  190. var newQua = new Quaternion();
  191. newQua.eulerAngles = Gyr * TimeGap;
  192. var quaGyr = LastQuaternion * newQua;
  193. float AccLengthToAngle = 180;//1倍引力差相当于多少度方差
  194. float MagLengthToAngle = 180;//1倍磁力差相当于多少度方差
  195. float GyrVariance = Last.Variance + (Gyr * TimeGap).magnitude * 0.05f;
  196. float AccVariance = Mathf.Max(TimeGap / 1, Mathf.Sqrt(Mathf.Pow((Acc.magnitude - 9.8f) / 9.8f * AccLengthToAngle, 2)+ Mathf.Pow(Vector3.Angle(Acc,Last.Acc) * 0.8f, 2)));
  197. float MagVariance = Mathf.Max(TimeGap / 0.2f,Mathf.Sqrt(Mathf.Pow((Mag.magnitude - 1) / 1 * MagLengthToAngle, 2) + Mathf.Pow(Vector3.Angle(Mag, Last.Mag) * 0.05f, 2)));
  198. state.Variance = state.Variance * AccVariance / (state.Variance + AccVariance);
  199. state.Variance = state.Variance * MagVariance / (state.Variance + MagVariance);
  200. var quaAccMag = o0Project.o0.FormQuaternion(AccIdentity, MagIdentity, Acc, Mag, AccVariance / (AccVariance + MagVariance));
  201. var quaMinRate = GyrVariance / (GyrVariance + Mathf.Max(AccVariance, MagVariance));
  202. var quaMaxRate = GyrVariance / (GyrVariance + Mathf.Min(AccVariance, MagVariance));
  203. Quaternion quaFirst = Quaternion.Slerp(quaGyr, quaAccMag, quaMinRate).normalized;
  204. float quaSecondRate = (quaMaxRate - quaMinRate) / (1 - quaMinRate);
  205. state.Qua = AccVariance < MagVariance ? o0Project.o0.FormQuaternion(quaFirst, AccIdentity, Acc, quaSecondRate): o0Project.o0.FormQuaternion(quaFirst, MagIdentity, Mag, quaSecondRate);
  206. return state.Qua;
  207. }
  208. //转换读取的数据,无符号->有符号
  209. float TwoByteToFloat(byte b1, byte b2)
  210. {
  211. ushort twoByte = (ushort) (b1 * 256 + b2);
  212. short shortNum = (short) twoByte;
  213. return (float) shortNum;
  214. }
  215. o0MagneticCalibrater MagCalibrater;
  216. o0Vector3Filter MagFilter = new o0Vector3Filter();
  217. long msOld = 0;
  218. public AimHandler(Transform controlObj, Button SetIdentity, Button CalibrationButton, Text MagScaleText)
  219. {
  220. this.controlObj = controlObj;
  221. this.SetIdentity = SetIdentity;
  222. this.CalibrationButton = CalibrationButton;
  223. this.MagScaleText = MagScaleText;
  224. if (SetIdentity != null)
  225. {
  226. SetIdentity.onClick.AddListener(DoIdentity);
  227. }
  228. MagCalibrater = new o0MagneticCalibrater();
  229. string caliraterDataStr = PlayerPrefs.GetString("o0MagneticCalibrater");
  230. if (caliraterDataStr.Length > 0)
  231. {
  232. string[] dataStrs = caliraterDataStr.Split(',');
  233. if (dataStrs.Length == 6)
  234. {
  235. MagCalibrater._Center = new Vector3(float.Parse(dataStrs[0]), float.Parse(dataStrs[1]), float.Parse(dataStrs[2]));
  236. MagCalibrater._Radius = new Vector3(float.Parse(dataStrs[3]), float.Parse(dataStrs[4]), float.Parse(dataStrs[5]));
  237. }
  238. }
  239. if (CalibrationButton != null)
  240. {
  241. CalibrationButton.onClick.AddListener(delegate {
  242. if (MagCalibrater.Calibration)
  243. {
  244. MagCalibrater.Calibration = false;
  245. CalibrationButton.GetComponentInChildren<Text>().text = "开始磁场校准";
  246. float[] dataFloats = new float[6];
  247. dataFloats[0] = MagCalibrater.Center.x;
  248. dataFloats[1] = MagCalibrater.Center.y;
  249. dataFloats[2] = MagCalibrater.Center.z;
  250. dataFloats[3] = MagCalibrater.Radius.x;
  251. dataFloats[4] = MagCalibrater.Radius.y;
  252. dataFloats[5] = MagCalibrater.Radius.z;
  253. string dataStr = String.Join(",", dataFloats);
  254. PlayerPrefs.SetString("o0MagneticCalibrater", dataStr);
  255. }
  256. else
  257. {
  258. MagCalibrater.Calibration = true;
  259. CalibrationButton.GetComponentInChildren<Text>().text = "停止磁场校准";
  260. }
  261. });
  262. }
  263. }
  264. public void OnDataReceived(byte[] bytes)
  265. {
  266. Debug.Log("瞄准模块数据长度" + bytes.Length);
  267. if (bytes.Length != 26)
  268. {
  269. if (bytes[3] == 125)
  270. {
  271. DoIdentity();
  272. }
  273. return;
  274. }
  275. if (bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0 && bytes[8] == 0 && bytes[9] == 0)
  276. return;
  277. if (bytes[16] == 0 && bytes[17] == 0 && bytes[18] == 0 && bytes[19] == 0 && bytes[20] == 0 && bytes[21] == 0)
  278. return;
  279. float ax = -TwoByteToFloat(bytes[4], bytes[5]);
  280. float ay = TwoByteToFloat(bytes[6], bytes[7]);
  281. float az = -TwoByteToFloat(bytes[8], bytes[9]);
  282. ax = ax / 32768 * 16;
  283. ay = ay / 32768 * 16;
  284. az = az / 32768 * 16;/**/
  285. Acc = new Vector3(ax, ay, az);
  286. float roll = TwoByteToFloat(bytes[10], bytes[11]);
  287. float pitch = TwoByteToFloat(bytes[12], bytes[13]);
  288. float yaw = TwoByteToFloat(bytes[14], bytes[15]);
  289. roll = -roll / 32768 * 2000;
  290. pitch = pitch / 32768 * 2000;
  291. yaw = -yaw / 32768 * 2000;
  292. Gyr = new Vector3(roll, pitch, yaw) / 1000;
  293. var gyr = new Vector3(roll, pitch, yaw) / 1000 * 20;
  294. float x = TwoByteToFloat(bytes[16], bytes[17]);
  295. float y = TwoByteToFloat(bytes[18], bytes[19]);
  296. float z = -TwoByteToFloat(bytes[20], bytes[21]);
  297. var mag = new Vector3(x, y, z);
  298. Mag = mag / 32768 * 256;
  299. if(Mag.x > -128 && Mag.y > -128 && Mag.z > -128 && Mag.x < 128 && Mag.y < 128 && Mag.z < 128)
  300. {
  301. Mag = MagCalibrater.Update(Mag);
  302. if (MagScaleText != null)
  303. {
  304. MagScaleText.text = MagCalibrater._Radius.ToString() + MagCalibrater.CalibratCompletionPercentage() + "%";
  305. }
  306. }
  307. var ms = (((long)bytes[22]) *60 + bytes[23])*1000 + (long)TwoByteToFloat(bytes[1], bytes[2]);
  308. if(msOld == default)
  309. {
  310. msOld = ms;
  311. return;
  312. }
  313. TimeGap = ms - msOld;
  314. msOld = ms;
  315. newRotation = o06DOFUpdate(Acc * 10, Gyr, Mag, TimeGap);
  316. receiveDataCount++;
  317. if (!hasAutoIdentity && receiveDataCount == 5) {
  318. doIdentity = true;
  319. }
  320. }
  321. void DoIdentity()
  322. {
  323. if (hasAutoIdentity)
  324. {
  325. doIdentity = true;
  326. Debug.Log("reset identity");
  327. }
  328. }
  329. public void Update()
  330. {
  331. if (hasAutoIdentity && controlObj != null)
  332. {
  333. controlObj.transform.localRotation = Quaternion.Lerp(controlObj.transform.localRotation, newRotation, Time.deltaTime * 6);
  334. }
  335. if (doIdentity)
  336. {
  337. AccIdentity = AccOld;
  338. MagIdentity = MagOld;
  339. States.Last().Qua = Quaternion.identity;
  340. if (controlObj != null)
  341. {
  342. controlObj.transform.localRotation = Quaternion.identity;
  343. }
  344. doIdentity = false;
  345. hasAutoIdentity = true;
  346. }
  347. }
  348. int receiveDataCount = 0;
  349. bool doIdentity = false;
  350. bool hasAutoIdentity = false;
  351. Quaternion newRotation;
  352. Quaternion baseRotation = new Quaternion(0, 0, 0, 1);
  353. public void InitAutoIdentity()
  354. {
  355. receiveDataCount = 0;
  356. doIdentity = false;
  357. hasAutoIdentity = false;
  358. }
  359. }