ShootCheck.cs 10 KB

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