ConnectAdvertising.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using ArduinoBluetoothAPI;
  4. using System;
  5. using System.Text;
  6. using UnityEngine.UI;
  7. namespace DuckHunter
  8. {
  9. public class ConnectAdvertising : MonoBehaviour
  10. {
  11. Button advertisingBtn;
  12. Text advertisingText;
  13. GameObject connectTip;
  14. float speed = 10.0f;
  15. Vector3 targetPos = Vector3.zero;
  16. private BluetoothHelper helper;
  17. private BluetoothHelperCharacteristic characteristicWrite;
  18. private BluetoothHelperService bluetoothService;
  19. private bool isScanning;
  20. private bool isConnecting;
  21. private string data;
  22. private string tempVector;
  23. private string tmp;
  24. private string targetDeviceName = "SLAM_Advertiser";
  25. private string deviceName = "";
  26. string targetDeviceService = "0000fff1";
  27. string targetDeviceCharacteristicWrite = "0000ff11";
  28. string targetDeviceCharacteristicNotify = "0000ff11";
  29. private LinkedList<BluetoothDevice> devices;
  30. public GUIBox gUIBox;
  31. void Awake()
  32. {
  33. GameObject AdVertiserManagerObj = GameObject.Find("AdVertiserManager");
  34. if (AdVertiserManagerObj)
  35. {
  36. //刷新一次持久化对象的状态
  37. AdVertiserManagerObj.GetComponent<ConnectAdvertising>().OnUpdateState();
  38. Destroy(gameObject);
  39. return;
  40. }
  41. DontDestroyOnLoad(gameObject);
  42. transform.name = "AdVertiserManager";
  43. OnUpdateState();
  44. }
  45. public void OnUpdateState()
  46. {
  47. advertisingBtn = GameObject.Find("GameManager/GameUI/ConnectButton").GetComponent<Button>();
  48. advertisingText = advertisingBtn.transform.Find("Text").GetComponent<Text>();
  49. connectTip = GameObject.Find("GameManager/GameUI/ConnectTip");
  50. connectTip.SetActive(true);
  51. if (helper == null)
  52. return;
  53. if (!helper.isConnected() && !isScanning && !isConnecting)
  54. {
  55. //未连接,未扫描,不是连接中
  56. advertisingText.text = "点击连接";
  57. }
  58. else if (!helper.isConnected() && isScanning)
  59. {
  60. //扫描中
  61. advertisingText.text = "扫描中...";
  62. }
  63. else if (helper.isConnected())
  64. {
  65. //已连接
  66. advertisingText.text = "已连接";
  67. connectTip.SetActive(false);
  68. }
  69. }
  70. // Start is called before the first frame update
  71. void Start()
  72. {
  73. //if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  74. //{
  75. // Debug.Log("蓝牙未打开!");
  76. // return;
  77. //}
  78. tempVector = "";
  79. data = "";
  80. tmp = "";
  81. try
  82. {
  83. BluetoothHelper.BLE = true;
  84. helper = BluetoothHelper.GetInstance();
  85. helper.OnConnected += OnConnected;
  86. helper.OnConnectionFailed += OnConnectionFailed;
  87. helper.OnScanEnded += OnScanEnded;
  88. helper.OnCharacteristicChanged += (helper, value, characteristic) =>
  89. {
  90. byte[] bytes = value;
  91. if (bytes.Length > 1)
  92. {
  93. // StringBuilder builder = new StringBuilder();
  94. // builder.Append(string.Format("{0:X2}", bytes[0]));
  95. string flag = getBytesToIndex(bytes, 0);
  96. //Debug.Log("flag:" + ToHexStrFromByte(value));
  97. if (flag.ToLower() == "ff")
  98. {
  99. float endXFloat = onVectorValue(bytes, 2);
  100. float endYFloat = onVectorValue(bytes, 5);
  101. //Debug.Log("endFloat:(" + endXFloat.ToString("F4") + "," + endYFloat.ToString("F4") + ")");
  102. //data += "\n<" + " 输出:("+ endXFloat.ToString("F4")+","+ endYFloat.ToString("F4")+")";
  103. //tempVector = "(" + endXFloat.ToString("F4") + "," + endYFloat.ToString("F4") + ")";
  104. //更新对应的屏幕坐标
  105. //if (endXFloat >= 0 && endYFloat >= 0)
  106. CrossHair.Instance.transform.position = new Vector3(endXFloat * Screen.width, endYFloat * Screen.height, 0);
  107. }
  108. else if (flag.ToLower() == "aa")
  109. {
  110. //模拟射击
  111. float endXFloat = onVectorValue(bytes, 2);
  112. float endYFloat = onVectorValue(bytes, 5);
  113. Debug.Log("aa endFloat:(" + endXFloat.ToString("F4") + "," + endYFloat.ToString("F4") + ")");
  114. CrossHair.Instance.transform.position = new Vector3(endXFloat * Screen.width, endYFloat * Screen.height, 0);
  115. GameManager.Instance.OnModuleShooting(10);
  116. }
  117. else if (flag.ToLower() == "bb")
  118. {
  119. //切换游戏光标
  120. string _crosshair = getBytesToIndex(bytes, 1);
  121. // Debug.Log("_crosshair:" + _crosshair);
  122. // Debug.Log("_crosshair.ToLower():" + _crosshair.ToLower());
  123. if (_crosshair.ToLower() == "00")
  124. {
  125. //显示游戏光标
  126. gUIBox.onSetCrossHairImage(true);
  127. PlayerPrefs.SetInt("CrossHairImageActive", 1);
  128. }
  129. else if (_crosshair.ToLower() == "01")
  130. {
  131. //隐藏游戏光标
  132. gUIBox.onSetCrossHairImage(false);
  133. PlayerPrefs.SetInt("CrossHairImageActive", 0);
  134. }
  135. }
  136. }
  137. else
  138. {
  139. //Debug.Log(String.Join(",", bytes));
  140. Debug.Log(characteristic.getName() + " 输出: " + ToHexStrFromByte(value));
  141. //System.Text.Encoding.ASCII.GetString(value)
  142. data += "\n<" + characteristic.getName() + " 输出: " + ToHexStrFromByte(value);
  143. }
  144. };
  145. connectTip.SetActive(false);
  146. // if (BluetoothHelperAndroid.RequestBluetoothPermissions(() =>
  147. // {
  148. // isScanning = helper.ScanNearbyDevices();
  149. // }, (permission) =>
  150. // {
  151. // if (permission.Contains("LOCATION"))
  152. // {
  153. // Debug.Log("exception2");
  154. // }
  155. // else if (permission.Contains("BLUETOOTH"))
  156. // {
  157. // Debug.Log("exception3");
  158. // }
  159. // })) return;
  160. // isScanning = helper.ScanNearbyDevices();
  161. }
  162. catch (Exception e)
  163. {
  164. Debug.LogError(e);
  165. }
  166. }
  167. string getBytesToIndex(byte[] bytes, int index)
  168. {
  169. StringBuilder builderCrosshair = new StringBuilder();
  170. builderCrosshair.Append(string.Format("{0:X2}", bytes[index]));
  171. return builderCrosshair.ToString().Trim();
  172. }
  173. float onVectorValue(byte[] bytes, int startIndex)
  174. {
  175. //整数部分
  176. string intPartHex = string.Format("{0:X2}", bytes[startIndex]).ToString().Trim(); ;
  177. int intPartNumber = Convert.ToInt32(intPartHex, 16);
  178. StringBuilder builder = new StringBuilder();
  179. for (int i = 0; i < 2; i++)
  180. {
  181. builder.Append(string.Format("{0:X2}", bytes[i + startIndex + 1]));
  182. }
  183. string dataHex = builder.ToString().Trim();
  184. int decimalPartNumber = Convert.ToInt32(dataHex, 16);
  185. return intPartNumber + (float)decimalPartNumber / 32768;
  186. }
  187. void OnScanEnded(BluetoothHelper helper, LinkedList<BluetoothDevice> devices)
  188. {
  189. if (devices.Count == 0)
  190. {
  191. isScanning = helper.ScanNearbyDevices();
  192. Debug.Log("OnScanEnded:" + devices.Count);
  193. return;
  194. }
  195. this.isScanning = false;
  196. foreach (BluetoothDevice device in devices)
  197. {
  198. if (device.DeviceName == targetDeviceName)
  199. {
  200. deviceName = device.DeviceName;
  201. helper.setDeviceName(deviceName);
  202. try
  203. {
  204. helper.Connect();
  205. isConnecting = true;
  206. }
  207. catch (Exception)
  208. {
  209. isConnecting = false;
  210. }
  211. Debug.Log("匹配设备 " + device.DeviceName);
  212. return;
  213. }
  214. }
  215. }
  216. void OnConnected(BluetoothHelper helper)
  217. {
  218. isConnecting = false;
  219. connectTip.SetActive(false);
  220. Debug.Log("连接成功:" + helper.getDeviceName());
  221. foreach (BluetoothHelperService service in helper.getGattServices())
  222. {
  223. if (service.getName().ToLower().StartsWith(targetDeviceService))
  224. {
  225. bluetoothService = service;
  226. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  227. {
  228. if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicWrite))
  229. {
  230. characteristicWrite = characteristic;
  231. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  232. ch.setService(bluetoothService.getName());
  233. helper.Subscribe(ch);
  234. }
  235. }
  236. Debug.Log("Connected");
  237. }
  238. }
  239. }
  240. void OnConnectionFailed(BluetoothHelper helper)
  241. {
  242. isConnecting = false;
  243. Debug.Log("Connection lost");
  244. advertisingText.text = "点击连接";
  245. }
  246. void Update()
  247. {
  248. if (helper == null)
  249. return;
  250. // if (targetPos != CrossHair.Instance.transform.position)
  251. // {
  252. // Vector3 lerp = Vector3.Lerp(CrossHair.Instance.transform.position, targetPos, Time.deltaTime * speed);
  253. // CrossHair.Instance.transform.position = lerp;
  254. // }
  255. if (!helper.isConnected() && !isScanning && !isConnecting)
  256. {
  257. //未连接,未扫描,不是连接中
  258. advertisingText.text = "点击连接";
  259. }
  260. else if (!helper.isConnected() && isScanning)
  261. {
  262. //扫描中
  263. advertisingText.text = "扫描中...";
  264. }
  265. else if (helper.isConnected())
  266. {
  267. //已连接
  268. advertisingText.text = "已连接";
  269. }
  270. }
  271. public void OnAdvertisingClick()
  272. {
  273. // float _randomX = (float)new System.Random().Next(0, 100) / 100;
  274. // float _randomY = (float)new System.Random().Next(0, 100) / 100;
  275. // Debug.Log("_random:"+_randomX + "," + _randomY);
  276. // CrossHair.Instance.transform.position = new Vector3(_randomX * Screen.width, _randomY* Screen.height, 0);
  277. if (helper == null)
  278. return;
  279. if (!helper.isConnected() && !isScanning && !isConnecting)
  280. {
  281. //未连接,未扫描,不是连接中
  282. //if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  283. //{
  284. // Debug.Log("exception1");
  285. // return;
  286. //}
  287. //if (BluetoothHelperAndroid.RequestBluetoothPermissions(() =>
  288. // {
  289. // isScanning = helper.ScanNearbyDevices();
  290. // }, (permission) =>
  291. // {
  292. // if (permission.Contains("LOCATION"))
  293. // {
  294. // Debug.Log("exception2");
  295. // }
  296. // else if (permission.Contains("BLUETOOTH"))
  297. // {
  298. // Debug.Log("exception3");
  299. // }
  300. // })) return;
  301. isScanning = helper.ScanNearbyDevices();
  302. }
  303. else if (!helper.isConnected() && isScanning)
  304. {
  305. //扫描中
  306. advertisingText.text = "扫描中...";
  307. }
  308. else if (helper.isConnected())
  309. {
  310. //已连接,断开连接
  311. helper.Disconnect();
  312. }
  313. }
  314. void OnDestroy()
  315. {
  316. if (helper != null)
  317. helper.Disconnect();
  318. }
  319. /// <summary>
  320. /// 字节数组转16进制字符串:空格分隔
  321. /// </summary>
  322. /// <param name="byteDatas"></param>
  323. /// <returns></returns>
  324. public string ToHexStrFromByte(byte[] byteDatas)
  325. {
  326. StringBuilder builder = new StringBuilder();
  327. for (int i = 0; i < byteDatas.Length; i++)
  328. {
  329. builder.Append(string.Format("{0:X2} ", byteDatas[i]));
  330. }
  331. return builder.ToString().Trim();
  332. }
  333. }
  334. }