123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327 |
- using LitJson;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- using UnityEngine;
- using UnityEngine.Android;
- using uPLibrary.Networking.M2Mqtt.Messages;
- using static QTTManager;
- public class MQTTClient : MonoSingleton<MQTTClient>
- {
- public string OnlineType = "online/";
- string password = null;// 需要根据服务器设置
- // public static byte[] bytes;
- // public static byt ta;
- QTTManager qt;
- // Start is called before the first frame update
- void Start()
- {
- // 请求文件读取和写入权限
- if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead) ||
- !Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
- {
- Permission.RequestUserPermission(Permission.ExternalStorageRead);
- Permission.RequestUserPermission(Permission.ExternalStorageWrite);
- }
- //bytes = (Resources.Load("emqxsl-ca") as TextAsset).bytes;
-
- //Debug.Log(" DGJ ===> emqxsl-ca.bytes "+ bytes.Length);
- }
- Queue<MqttMsgPublishEventArgs> rlist = new Queue<MqttMsgPublishEventArgs>();
- private void OnReceived(MqttMsgPublishEventArgs obj)
- {
- rlist.Enqueue(obj);
- }
- private void OnConnecting()
- {
- Debug.Log("MQtt 连接中");
- }
- private void onSucceed()
- {
- Subscribe();
- }
- private void onFaild()
- {
- Debug.Log("MQtt 连接失败");
- }
- // Update is called once per frame
- void Update()
- {
- if (rlist.Count > 0)
- {
- for (int i = 0; i < rlist.Count; i++)
- {
- OnUnityReceived(rlist.Dequeue());
- }
- }
- }
- //MQTT接收到的数据
- public void OnUnityReceived(MqttMsgPublishEventArgs obj)
- {
- string msg = Encoding.UTF8.GetString(obj.Message);
- Debug.Log("uid => " + obj.Topic + ":\n" + msg);
- try
- {
- JsonData data = JsonMapper.ToObject(msg);
- Debug.Log(" DGJ === > " + data["type"].ToString());
- switch (data["type"].ToString())
- {
- case "CamPos":
- Debug.Log("DGJ ===> CamPos");
- // 根据 uid 同步Player 位置 如果没有就创建
- MultiPlayerManager.Instance.ReceivedCamPos(obj.Topic, data);
- break;
- case "ActiveSp":
- // 同步对应景点的开关
- MultiPlayerManager.Instance.ReceivedActiveSp( data);
- break;
- case "ActiveVideo":
- // 同步播放器的对应状态
- MultiPlayerManager.Instance.ReceivedActiveVideo(data);
- break;
- default:
- break;
- }
- }
- catch
- {
- return;
- }
- }
- private void OnDestroy()
- {
- DisConnect();
- }
- public string auth;
- public string topicPrefix;
- public string clientIdPrefix;
- public void setData(JsonData data)
- {
- //MQTTClinet 连接
- MQTTClient.Instance.SetUserName(data["auth"].ToString());
- MQTTClient.Instance.SetFront(data["topicPrefix"].ToString());
- clientIdPrefix = data["clientIdPrefix"].ToString();
- }
- public void PublicPosScene(string sid,string pos)
- {
- ;
- if (qt != null && qt.IsConnect())
- {
- // Debug.Log("发送===》"+ "10001/realtime/project/" + sid+"_"+ pos);
- publish("10001/realtime/project/" + sid,Encoding.UTF8.GetBytes(pos));
- }
- }
- public void SubscribeScene(string sid)
- {
- Debug.Log(" DGJ =====> 订阅 " + topicPrefix + sid);
- Debug.Log(" DGJ =====> 订阅 " + topicPrefix + OnlineType + sid);
- ushort s = qt.Subscribe(
- new string[]
- {
- topicPrefix+sid,
- topicPrefix+OnlineType+sid
- },
- new byte[]
- {
- MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE,
- MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE
- });
- }
- public void SetUserName(string username)
- {
- if (auth != null)
- this.auth = username;
- }
- public void SetFront(string front)
- {
- if (topicPrefix != null)
- this.topicPrefix = front;
- }
- public string id;
- public string rid;
- //连接
- public void Connect()
- {
-
- Debug.Log("DGJ ===> MQTT ");
- if (DeviceType.type == "Phone")
- {
- id = UserInfo.Instance.Account + "_Phone";
- rid = clientIdPrefix+UserInfo.Instance.Account + "_Glasses";
- }
- else
- {
- id = UserInfo.Instance.Account + "_Glasses";
- rid = clientIdPrefix + UserInfo.Instance.Account + "_Phone";
- }
- DisConnect();
-
- Debug.Log("mqtturl=====》" + HttpAction.Instance.mqtturl+"_"+ HttpAction.Instance.officeport+ (Resources.Load("emqxsl-ca") as TextAsset).bytes.Length);
- qt = new QTTManager(topicPrefix+id, auth, password, HttpAction.Instance.mqtturl, HttpAction.Instance.officeport);
- qt.Connect();
- StartCoroutine(Reconnection());
- qt.ConnectionFailed -= onFaild;
- qt.ConnectionSucceeded -= onSucceed;
- qt.OnConnecting -= OnConnecting;
- qt.OnReceived -= OnReceived;
- qt.OnClose -= OnClose;
- qt.ConnectionFailed += onFaild;
- qt.ConnectionSucceeded += onSucceed;
- qt.OnConnecting += OnConnecting;
- qt.OnReceived += OnReceived;
- qt.OnClose += OnClose;
- }
- private void OnClose(EventArgs obj)
- {
- Debug.Log("断开连接");
-
- }
- private IEnumerator Reconnection()
- {
- while (true)
- {
- yield return new WaitForSeconds(5);
- if(qt!=null&&!qt.IsConnect())
- {
- Debug.Log(" DGJ ===> Reconnection ");
- Connect();
- }
- }
- }
- //断开连接
- public void DisConnect()
- {
- if (qt != null && qt.IsConnect())
- qt.DisConnect();
- }
- //订阅
- public void Subscribe()
- {
- Debug.Log(" DGJ =====> Subscribe "+ id);
- ushort s = qt.Subscribe(
- new string[]
- {
- topicPrefix+id
- },
- new byte[]
- {
-
- MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE
- });
- Debug.Log(" DGJ =====> Subscribe2");
-
- }
- public void StartSendCameraPos()
- {
- StartCoroutine(sendCameraPos());
- }
- //眼镜端像手机端发送实时位置
- IEnumerator sendCameraPos()
- {
- Debug.Log("DGJ =====> sendCameraPos" + qt.IsConnect());
- while (true)
- {
- if(qt!=null&& qt.IsConnect())
- {
- JsonData json = new JsonData();
- json["type"] = "CamPos";
- // json["x"] = OpenXRCamera.Instance.head.position.x;
- //json["y"] = OpenXRCamera.Instance.head.position.y;
- //json["z"] = OpenXRCamera.Instance.head.position.z;
- json["x"] = GameManager.Instance.Player.transform.localPosition.x;
- json["y"] = GameManager.Instance.Player.transform.localPosition.y;
- json["z"] = GameManager.Instance.Player.transform.localPosition.z;
- json["Sid"] = "sid";//选择的场景id
- publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
- }
-
- yield return new WaitForSeconds(0.1f);
- }
- }
- //眼镜发送触发的景点
- public void sendActiveSp(string spid,bool isOpen)
- {
- JsonData json = new JsonData();
- json["type"] = "ActiveSp";
- json["Sid"] = "sid";//选择的场景id
- json["spid"] = spid;//景点id
- json["isOpen"] = isOpen;//是否打开
- publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
- Debug.Log("MQtt 发送manage");
- }
- //眼镜发送触发的视频
- public void sendActiveVideo(string spid,string videoId, bool isplay,float jindu)
- {
- JsonData json = new JsonData();
- json["type"] = "ActiveVideo";
- json["Sid"] = "sid";//选择的场景id
- json["spid"] = spid;//景点id
- json["videoId"] = videoId;//视频id
- json["isplay"] = isplay;//是否播放
- json["jindu"] = jindu;//视频进度
- publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
- Debug.Log("MQtt 发送manage");
- }
- void publish(string str,byte[] bs)
- {
- if(qt!=null&& qt.IsConnect())
- {
- // Debug.Log(id + " DGJ publish =====> " + front+rid + " " + bs.Length);
- qt.Publish(str, bs, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
- }
- else
- {
- Debug.LogError(" MQTT 未连接 ");
- }
-
- }
- }
|