| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System;
- using UnityEngine;
- using UnityEngine.UI;
- using BestHTTP.WebSocket;
- [Serializable]
- class JCData {
- public string uuid;
- public int type;
- public string func;
- public string[] args;
- }
- public class BluetoothClient : MonoBehaviour
- {
- WebSocket ws;
- bool loaded = false;
- [SerializeField] string serverIP = "110.43.54.43";
- [SerializeField] Text text;
- public static System.Action<byte, byte[]> onDataReceived;
- static BluetoothClient ins;
- void Start()
- {
- ins = this;
- string uri = "ws://" + serverIP + ":9888/BLE";
- ws = new WebSocket(new Uri(uri));
- ws.OnOpen += OnOpen;
- ws.OnMessage += OnMessage;
- ws.Open();
- }
- void OnOpen(WebSocket webSocket)
- {
- ws.Send(PackData("loadTempEntity", new string[]{}, 0));
- }
- void OnMessage(WebSocket webSocket, string text)
- {
- JCData data = JsonUtility.FromJson<JCData>(text);
- if (data.func == "receiveData")
- {
- string byteStr = data.args[1];
- string[] byteStrs = byteStr.Split(',');
- byte[] bytes = new byte[byteStrs.Length];
- for (int i = 0; i < bytes.Length; i++)
- {
- bytes[i] = Byte.Parse(byteStrs[i]);
- }
- Log("接收数据\n" + byteStr);
- if (onDataReceived != null)
- {
- onDataReceived(byte.Parse(data.args[0]), bytes);
- }
- }
- else if (data.func == "loadTempEntity")
- {
- loaded = true;
- }
- }
- string PackData(string func, string[] args, int type)
- {
- JCData data = new JCData();
- data.uuid = "";
- data.type = type;
- data.func = func;
- data.args = args;
- return JsonUtility.ToJson(data);
- }
- public static void UploadData(byte sign, byte[] bytes)
- {
- if (ins && ins.loaded)
- {
- string data = String.Join(",", bytes);
- ins.ws.Send(ins.PackData("uploadData", new string[]{sign.ToString(), data}, 1));
- ins.Log("正在上传数据\n" + bytes);
- }
- }
- void Log(string text) {
- if (this.text != null)
- {
- this.text.text = text;
- }
- }
- }
|