ShootCheck.cs 10 KB

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