BluetoothClient.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. using JCEngineCore;
  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. [SerializeField] string serverIP = "110.43.54.43";
  15. [SerializeField] Text text;
  16. BleDebugClient client = new BleDebugClient();
  17. public static System.Action<byte, byte[]> onDataReceived;
  18. public static BluetoothClient ins;
  19. void Start()
  20. {
  21. ins = this;
  22. JCEngine.bootNew("ws://" + serverIP + ":9888/BLE", client);
  23. }
  24. public static void UploadData(byte sign, byte[] bytes)
  25. {
  26. if (ins && ins.client.isValid)
  27. {
  28. string data = String.Join(",", bytes);
  29. ins.client.call("uploadData", sign.ToString(), data);
  30. ins.Log("正在上传数据\n" + data);
  31. }
  32. }
  33. public static void UploadError(params string[] errors) {
  34. if (ins) {
  35. ins.client.call("showError", string.Join("\n", errors));
  36. }
  37. }
  38. public void Log(string text) {
  39. if (this.text != null)
  40. {
  41. this.text.text = text;
  42. }
  43. }
  44. }
  45. class BleDebugClient : JCEntity {
  46. public void receiveData(string sign, string byteStrList) {
  47. string[] byteStrs = byteStrList.Split(',');
  48. byte[] bytes = new byte[byteStrs.Length];
  49. for (int i = 0; i < bytes.Length; i++)
  50. {
  51. bytes[i] = Byte.Parse(byteStrs[i]);
  52. }
  53. BluetoothClient.ins.Log("接收数据\n" + byteStrList);
  54. BluetoothClient.onDataReceived?.Invoke(byte.Parse(sign), bytes);
  55. }
  56. }