ShootCheck.cs 10 KB

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