ShootCheck.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 Awake()
  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. if (serverIP.Length == 0) serverIP = "192.168.101.14";
  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. string str1 = "byte=";
  147. if (webSocket != null)
  148. {
  149. for (int i = 0; i < bytes.Length-1; i++)
  150. {
  151. str1+= bytes[i];
  152. }
  153. // webSocket.Send(str2);
  154. }
  155. string str2 = "";
  156. if (transportMode == 0)
  157. {
  158. for (int i = 0; i < bytes.Length / 6; i++)
  159. {
  160. float acc = ToAcceleratedSpeed(bytes[i * 6 + 4], bytes[i * 6 + 5]);
  161. string t = "(采样时间:"+(int)bytes[i * 6 + 0] + "分"+ (int)bytes[i * 6 + 1]+"秒"+ TwoByteToInt(bytes[i * 6 + 2], bytes[i * 6 + 3])+"毫秒)" ;
  162. str2 += "加速度:"+ acc + t + "\n";
  163. if (ins.check(0, acc, 0, t) && ArmBow.ins)
  164. {
  165. ArmBow.ins.ADS_fire();
  166. }
  167. }
  168. }
  169. else if (transportMode == 1)
  170. {
  171. for (int i = 0; i < bytes.Length / 11; i++)
  172. {
  173. float ax = ToAcceleratedSpeed(bytes[i * 11 + 5], bytes[i * 11 + 6]);
  174. float ay = ToAcceleratedSpeed(bytes[i * 11 + 7], bytes[i * 11 + 8]);
  175. float az = ToAcceleratedSpeed(bytes[i * 11 + 9], bytes[i * 11 + 10]);
  176. string t = "(采样时间:"+(int)bytes[i * 11 + 3] + "分"+ (int)bytes[i * 11 + 4]+"秒"+ TwoByteToInt(bytes[i * 11 + 1], bytes[i * 11 + 2])+"毫秒)" ;
  177. str2 += "加速度:"+ay+t+"\n";
  178. if (ins.check(ax, ay, az, t) && ArmBow.ins)
  179. {
  180. ArmBow.ins.ADS_fire();
  181. }
  182. }
  183. }
  184. if (webSocket != null)
  185. {
  186. string str3 = str1+"\n"+str2;
  187. webSocket.Send(str3);
  188. }
  189. }
  190. float ToAcceleratedSpeed(byte b1, byte b2)
  191. {
  192. int value = TwoByteToInt(b1, b2);
  193. return (float)value / 32768 * LoginMgr.myUserInfo.arrowAccValue;
  194. }
  195. int TwoByteToInt(byte b1, byte b2)
  196. {
  197. ushort twoByte = (ushort)(b1 * 256 + b2);
  198. short shortNum = (short)twoByte;
  199. return (int)shortNum;
  200. }
  201. public float arrowWeight = 60; //实体模具箭重,单位克
  202. bool check(float ax, float ay, float az, string t)
  203. {
  204. float acc = ay;
  205. DebugLine.show(acc); //这个不需要注释,静态函数内置判断
  206. if (locked)
  207. {
  208. return false;
  209. }
  210. if (acc > cmd.getAcc())
  211. {
  212. if (acc > maxAcc)
  213. {
  214. maxAcc = acc;
  215. }
  216. if (acc > 15.9f && LoginMgr.myUserInfo.arrowAccValue == 16) {
  217. double p1 = -1.56729339506415;
  218. double p2 = 0.0397744840580165;
  219. double p3 = 4.73453844008481;
  220. float x = (keyAccList.Count + 1) * 2; //单位毫秒
  221. double y = 1.0 / (p1+p2*Mathf.Pow(x, 0.5f)*Mathf.Log(x)+p3/Mathf.Pow(x, 0.5f));
  222. acc = (float) y;
  223. }
  224. Vector3 keyAcc = new Vector3(ax, acc, az);
  225. keyAccList.Enqueue(keyAcc);
  226. keyTimeList.Enqueue(t);
  227. return false;
  228. }
  229. else if (acc < cmd.getAcc() && maxAcc != 0) {
  230. //积分求初速度
  231. shootSpeed = 0;
  232. float lasKeytAcc = 0;
  233. int keyAccIndex = 0;
  234. float timeInterval = 0.002f;
  235. float totalAx = 0;
  236. float totalAy = 0;
  237. float totalAz = 0;
  238. foreach (var keyAcc in keyAccList)
  239. {
  240. totalAx += Mathf.Abs(keyAcc.x);
  241. totalAy += Mathf.Abs(keyAcc.y);
  242. totalAz += Mathf.Abs(keyAcc.z);
  243. if (keyAccIndex > 0)
  244. {
  245. shootSpeed += keyAcc.y * timeInterval;
  246. shootSpeed -= (keyAcc.y - lasKeytAcc) * timeInterval / 2;
  247. }
  248. else if (keyAccIndex == 0 && keyAccList.Count == 1)
  249. {
  250. shootSpeed = keyAcc.y * timeInterval;
  251. }
  252. lasKeytAcc = keyAcc.y;
  253. keyAccIndex++;
  254. }
  255. //是不是合法射出
  256. bool isLegalShoot = totalAy > totalAx && totalAy > totalAz;
  257. if (isLegalShoot)
  258. {
  259. //加速度acc的单位是g,最后需要乘上
  260. shootSpeed *= 9.80665f;
  261. string strShootSpeed = "弓轨速度: " + shootSpeed + " 帧数: " + keyAccList.Count + "\n";
  262. shootSpeed = Mathf.Sqrt(shootSpeed * shootSpeed * arrowWeight / LoginMgr.myUserInfo.actualArrowWeight);
  263. strShootSpeed += "箭的速度: " + shootSpeed + "\n";
  264. string str1 = strShootSpeed + "/////////检测到射出的数据////////////:\n";
  265. for (int i=0;i<keyAccList.Count;i++)
  266. {
  267. float keyAcc = keyAccList.ElementAt(i).y;
  268. string time = keyTimeList.ElementAt(i);
  269. str1 += "加速度:"+keyAcc+time+"\n";
  270. }
  271. Debug.LogWarning(str1);
  272. if (webSocket != null)
  273. {
  274. webSocket.Send(str1+"/////////检测到射出的数据////////////:\n");
  275. }
  276. }
  277. //本轮计算结束
  278. keyAccList.Clear();
  279. keyTimeList.Clear();
  280. maxAcc = 0;
  281. Dolock();
  282. Invoke("Unlock", 1.8f);
  283. return isLegalShoot;
  284. }
  285. return false;
  286. }
  287. public string ShootByInfrared(byte[] bytes) {
  288. float time1 = ((bytes[5] << 8) + bytes[6]) * 0.1f;
  289. float time2 = ((bytes[7] << 8) + bytes[8]) * 0.1f;
  290. float speed = 0.05f / (time1 / 1000 + time2 / 1000);
  291. shootSpeed = Mathf.Sqrt(speed * speed * arrowWeight / LoginMgr.myUserInfo.actualArrowWeight);
  292. string logTxt = $"时长1:{time1}毫秒,时长2:{time2}毫秒,弓轨速度:{speed}m/s,箭的速度:{shootSpeed}m/s";
  293. Debug.Log(logTxt);
  294. try {
  295. ShootCheck.ins.webSocket.Send(logTxt);
  296. } catch (Exception) {}
  297. if (ArmBow.ins) ArmBow.ins.ADS_fire();
  298. return logTxt;
  299. }
  300. void Dolock()
  301. {
  302. locked = true;
  303. }
  304. void Unlock()
  305. {
  306. locked = false;
  307. }
  308. void Log(string text)
  309. {
  310. if (this.text)
  311. {
  312. this.text.text = text;
  313. } else {
  314. Debug.Log(text);
  315. }
  316. }
  317. }
  318. [Serializable]
  319. public class CMD {
  320. // public string ax = "y";
  321. // public int a = 6000;
  322. // public int r = 2;
  323. public string a = "y";
  324. public int a1 = 3;
  325. public int a2 = -3;
  326. public int r = 2;
  327. public float getAcc() {
  328. return a1;
  329. }
  330. }