BluetoothClient.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. using BestHTTP.WebSocket;
  5. [Serializable]
  6. class JCData {
  7. public string uuid;
  8. public int type;
  9. public string func;
  10. public string[] args;
  11. }
  12. public class BluetoothClient : MonoBehaviour
  13. {
  14. WebSocket ws;
  15. bool loaded = false;
  16. [SerializeField] string serverIP = "110.43.54.43";
  17. [SerializeField] Text text;
  18. public static System.Action<byte, byte[]> onDataReceived;
  19. static BluetoothClient ins;
  20. void Start()
  21. {
  22. ins = this;
  23. string uri = "ws://" + serverIP + ":9888/BLE";
  24. ws = new WebSocket(new Uri(uri));
  25. ws.OnOpen += OnOpen;
  26. ws.OnMessage += OnMessage;
  27. ws.Open();
  28. }
  29. void OnOpen(WebSocket webSocket)
  30. {
  31. ws.Send(PackData("loadTempEntity", new string[]{}, 0));
  32. }
  33. void OnMessage(WebSocket webSocket, string text)
  34. {
  35. JCData data = JsonUtility.FromJson<JCData>(text);
  36. if (data.func == "receiveData")
  37. {
  38. string byteStr = data.args[1];
  39. string[] byteStrs = byteStr.Split(',');
  40. byte[] bytes = new byte[byteStrs.Length];
  41. for (int i = 0; i < bytes.Length; i++)
  42. {
  43. bytes[i] = Byte.Parse(byteStrs[i]);
  44. }
  45. Log("接收数据\n" + byteStr);
  46. if (onDataReceived != null)
  47. {
  48. onDataReceived(byte.Parse(data.args[0]), bytes);
  49. }
  50. }
  51. else if (data.func == "loadTempEntity")
  52. {
  53. loaded = true;
  54. }
  55. }
  56. string PackData(string func, string[] args, int type)
  57. {
  58. JCData data = new JCData();
  59. data.uuid = "";
  60. data.type = type;
  61. data.func = func;
  62. data.args = args;
  63. return JsonUtility.ToJson(data);
  64. }
  65. public static void UploadData(byte sign, byte[] bytes)
  66. {
  67. if (ins && ins.loaded)
  68. {
  69. string data = String.Join(",", bytes);
  70. ins.ws.Send(ins.PackData("uploadData", new string[]{sign.ToString(), data}, 1));
  71. ins.Log("正在上传数据\n" + bytes);
  72. }
  73. }
  74. void Log(string text) {
  75. if (this.text != null)
  76. {
  77. this.text.text = text;
  78. }
  79. }
  80. }