BluetoothAim.cs 13 KB

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