ShootCheck.cs 10 KB

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