ShootCheck.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using ArduinoBluetoothAPI;
  7. using DG.Tweening;
  8. using UnityEngine.SceneManagement;
  9. using System.Linq;
  10. using BestHTTP.WebSocket;
  11. public class ShootCheck : MonoBehaviour
  12. {
  13. [SerializeField] Text text;
  14. CMD cmd = new CMD();
  15. bool locked = false;
  16. float maxAcc = 0;
  17. Queue<Vector3> keyAccList = new Queue<Vector3>();
  18. Queue<string> keyTimeList = new Queue<string>();
  19. public float shootSpeed;
  20. public static ShootCheck ins;
  21. [SerializeField] InputField ipInputField = default;
  22. WebSocket webSocket;
  23. void Start()
  24. {
  25. ins = this;
  26. BluetoothDispatcher.shoot = OnDataReceived;
  27. }
  28. //用户输入时的变化
  29. public void ChangedValue(string value)
  30. {
  31. ipInputField.ActivateInputField();
  32. Debug.Log("输入了"+value);
  33. }
  34. public void EndValue(string value)
  35. {
  36. Debug.Log("最终内容"+value);
  37. }
  38. //socket
  39. public void StartSocket()
  40. {
  41. //socket
  42. string ipStr = ipInputField.text;//ipInputField.GetComponentInChildren<Text>();
  43. string serverIP = ipStr;
  44. // serverIP = "172.16.20.57";
  45. string address = "ws://" + serverIP + ":8088/Ble/";
  46. webSocket = new WebSocket(new Uri(address));
  47. #if !UNITY_WEBGL
  48. webSocket.StartPingThread = true;
  49. #endif
  50. // Subscribe to the WS events
  51. webSocket.OnOpen += OnOpen;
  52. webSocket.OnMessage += OnMessageRecv;
  53. webSocket.OnBinary += OnBinaryRecv;
  54. webSocket.OnClosed += OnClosed;
  55. webSocket.OnError += OnError;
  56. // Debug.Log("OnOpen: ");
  57. // Start connecting to the server
  58. webSocket.Open();
  59. }
  60. public void Destroy()
  61. {
  62. if (webSocket != null)
  63. {
  64. webSocket.Close();
  65. webSocket = null;
  66. }
  67. }
  68. void OnOpen(WebSocket ws)
  69. {
  70. Debug.Log("OnOpen: ");
  71. webSocket.Send("unity");
  72. }
  73. void OnMessageRecv(WebSocket ws, string message)
  74. {
  75. Debug.LogFormat("OnMessageRecv: msg={0}", message);
  76. }
  77. void OnBinaryRecv(WebSocket ws, byte[] data)
  78. {
  79. Debug.LogFormat("OnBinaryRecv: len={0}", data.Length);
  80. }
  81. void OnClosed(WebSocket ws, UInt16 code, string message)
  82. {
  83. Debug.LogFormat("OnClosed: code={0}, msg={1}", code, message);
  84. webSocket = null;
  85. }
  86. void OnError(WebSocket ws, Exception ex)
  87. {
  88. string errorMsg = string.Empty;
  89. #if !UNITY_WEBGL || UNITY_EDITOR
  90. if (ws.InternalRequest.Response != null)
  91. {
  92. errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
  93. }
  94. #endif
  95. Debug.LogFormat("OnError: error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
  96. webSocket = null;
  97. }
  98. //socket
  99. [SerializeField] InputField ArmBowInputField = default;
  100. public void SetShootBackTime()
  101. {
  102. ArmBow.ins.shootBackTime=int.Parse(ArmBowInputField.text);
  103. }
  104. public void OnBluetoothReady(BluetoothShoot bluetoothShoot)
  105. {
  106. if (LoginMgr.myUserInfo.arrowAccValue == 16)
  107. {
  108. cmd.a = "y";
  109. }
  110. else
  111. {
  112. cmd.a = "x";
  113. }
  114. bluetoothShoot.WriteData(JsonUtility.ToJson(cmd).Replace("\"", ""));
  115. Sequence sequence = DOTween.Sequence();
  116. sequence.PrependInterval(1).AppendCallback(delegate() {
  117. canAdjustNormalOrHightMode = true;
  118. AdjustNormalOrHightMode();
  119. });
  120. sequence.SetUpdate(true);
  121. }
  122. //===普通模式和高速模式的切换===
  123. public bool canAdjustNormalOrHightMode = false;
  124. public int transportMode = 0;
  125. public void AdjustNormalOrHightMode()
  126. {
  127. if (!canAdjustNormalOrHightMode) return;
  128. try {
  129. // string sceneName = SceneManager.GetActiveScene().name;
  130. // if (sceneName == "Game")
  131. // {
  132. // transportMode = 1;
  133. // BluetoothShoot.ins.WriteData("HA");
  134. // }
  135. // else
  136. // {
  137. // transportMode = 0;
  138. // BluetoothShoot.ins.WriteData("NA");
  139. // }
  140. transportMode = 0;
  141. BluetoothShoot.ins.WriteData("NA");
  142. } catch (Exception) {}
  143. }
  144. public void OnDataReceived(byte[] bytes)
  145. {
  146. if (bytes.Length == 2)
  147. {
  148. DeviceBatteryView.ins.RenderBattery(2, bytes[0]);
  149. return;
  150. }
  151. string str1 = "byte=";
  152. if (webSocket != null)
  153. {
  154. for (int i = 0; i < bytes.Length-1; i++)
  155. {
  156. str1+= bytes[i];
  157. }
  158. // webSocket.Send(str2);
  159. }
  160. string str2 = "";
  161. if (transportMode == 0)
  162. {
  163. for (int i = 0; i < (bytes.Length -2 ) /6; i++)
  164. {
  165. float acc = ToAcceleratedSpeed(bytes[i * 6 + 5], bytes[i * 6 + 6]);
  166. string t = "(采样时间:"+(int)bytes[i * 6 + 3] + "分"+ (int)bytes[i * 6 + 4]+"秒"+ TwoByteToInt(bytes[i * 6 + 1], bytes[i * 6 + 2])+"毫秒)" ;
  167. str2 += "加速度:"+ acc + t + "\n";
  168. if (ins.check(0, acc, 0, t) && ArmBow.ins)
  169. {
  170. ArmBow.ins.ADS_fire();
  171. }
  172. }
  173. }
  174. else if (transportMode == 1)
  175. {
  176. for (int i = 0; i < bytes.Length / 11; i++)
  177. {
  178. float ax = ToAcceleratedSpeed(bytes[i * 11 + 5], bytes[i * 11 + 6]);
  179. float ay = ToAcceleratedSpeed(bytes[i * 11 + 7], bytes[i * 11 + 8]);
  180. float az = ToAcceleratedSpeed(bytes[i * 11 + 9], bytes[i * 11 + 10]);
  181. string t = "(采样时间:"+(int)bytes[i * 11 + 3] + "分"+ (int)bytes[i * 11 + 4]+"秒"+ TwoByteToInt(bytes[i * 11 + 1], bytes[i * 11 + 2])+"毫秒)" ;
  182. str2 += "加速度:"+ay+t+"\n";
  183. if (ins.check(ax, ay, az, t) && ArmBow.ins)
  184. {
  185. ArmBow.ins.ADS_fire();
  186. }
  187. }
  188. }
  189. if (webSocket != null)
  190. {
  191. string str3 = str1+"\n"+str2;
  192. webSocket.Send(str3);
  193. }
  194. }
  195. float ToAcceleratedSpeed(byte b1, byte b2)
  196. {
  197. int value = TwoByteToInt(b1, b2);
  198. return (float)value / 32768 * LoginMgr.myUserInfo.arrowAccValue;
  199. }
  200. int TwoByteToInt(byte b1, byte b2)
  201. {
  202. ushort twoByte = (ushort)(b1 * 256 + b2);
  203. short shortNum = (short)twoByte;
  204. return (int)shortNum;
  205. }
  206. bool check(float ax, float ay, float az, string t)
  207. {
  208. float acc = ay;
  209. DebugLine.show(acc); //这个不需要注释,静态函数内置判断
  210. if (locked)
  211. {
  212. return false;
  213. }
  214. if (acc > cmd.getAcc())
  215. {
  216. if (acc > maxAcc)
  217. {
  218. maxAcc = acc;
  219. }
  220. if (acc > 15.9f && LoginMgr.myUserInfo.arrowAccValue == 16) {
  221. double p1 = -1.56729339506415;
  222. double p2 = 0.0397744840580165;
  223. double p3 = 4.73453844008481;
  224. float x = (keyAccList.Count + 1) * 2; //单位毫秒
  225. double y = 1.0 / (p1+p2*Mathf.Pow(x, 0.5f)*Mathf.Log(x)+p3/Mathf.Pow(x, 0.5f));
  226. acc = (float) y;
  227. }
  228. Vector3 keyAcc = new Vector3(ax, ay, az);
  229. keyAccList.Enqueue(keyAcc);
  230. keyTimeList.Enqueue(t);
  231. return false;
  232. }
  233. else if (acc < cmd.getAcc() && maxAcc != 0) {
  234. //积分求初速度
  235. shootSpeed = 0;
  236. float lasKeytAcc = 0;
  237. int keyAccIndex = 0;
  238. float timeInterval = 0.002f;
  239. float totalAx = 0;
  240. float totalAy = 0;
  241. float totalAz = 0;
  242. foreach (var keyAcc in keyAccList)
  243. {
  244. totalAx += Mathf.Abs(keyAcc.x);
  245. totalAy += Mathf.Abs(keyAcc.y);
  246. totalAz += Mathf.Abs(keyAcc.z);
  247. if (keyAccIndex > 0)
  248. {
  249. shootSpeed += keyAcc.y * timeInterval;
  250. shootSpeed -= (keyAcc.y - lasKeytAcc) * timeInterval / 2;
  251. }
  252. else if (keyAccIndex == 0 && keyAccList.Count == 1)
  253. {
  254. shootSpeed = keyAcc.y * timeInterval;
  255. }
  256. lasKeytAcc = keyAcc.y;
  257. keyAccIndex++;
  258. }
  259. //是不是合法射出
  260. bool isLegalShoot = totalAy > totalAx && totalAy > totalAz;
  261. if (isLegalShoot)
  262. {
  263. //加速度acc的单位是g,最后需要乘上
  264. shootSpeed *= 9.80665f;
  265. //积分出来的值还是太小,需要一个倍率
  266. shootSpeed *= 20;
  267. string strShootSpeed = "初速度: " + shootSpeed + " 帧数: " + keyAccList.Count + "\n";
  268. string str1 = strShootSpeed + "/////////检测到射出的数据////////////:\n";
  269. for (int i=0;i<keyAccList.Count;i++)
  270. {
  271. float keyAcc = keyAccList.ElementAt(i).y;
  272. string time = keyTimeList.ElementAt(i);
  273. str1 += "加速度:"+keyAcc+time+"\n";
  274. }
  275. Debug.LogWarning(str1);
  276. if (webSocket != null)
  277. {
  278. webSocket.Send(str1+"/////////检测到射出的数据////////////:\n");
  279. }
  280. }
  281. //本轮计算结束
  282. keyAccList.Clear();
  283. keyTimeList.Clear();
  284. maxAcc = 0;
  285. Dolock();
  286. Invoke("Unlock", 1.8f);
  287. return isLegalShoot;
  288. }
  289. return false;
  290. }
  291. void Dolock()
  292. {
  293. locked = true;
  294. }
  295. void Unlock()
  296. {
  297. locked = false;
  298. }
  299. void Log(string text)
  300. {
  301. if (this.text)
  302. {
  303. this.text.text = text;
  304. } else {
  305. Debug.Log(text);
  306. }
  307. }
  308. }
  309. [Serializable]
  310. class CMD {
  311. // public string ax = "y";
  312. // public int a = 6000;
  313. // public int r = 2;
  314. public string a = "y";
  315. public int a1 = 3;
  316. public int a2 = -3;
  317. public int r = 2;
  318. public float getAcc() {
  319. return a1;
  320. }
  321. }