MQTTClient.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. using LitJson;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using UnityEngine;
  7. using UnityEngine.Android;
  8. using uPLibrary.Networking.M2Mqtt.Messages;
  9. using static QTTManager;
  10. public class MQTTClient : MonoSingleton<MQTTClient>
  11. {
  12. string front = "client/";
  13. string id = "";
  14. string username = "u@unity3";// 需要根据服务器设置
  15. string password = null;// 需要根据服务器设置
  16. string rid = "mqttx_b4c02ddc"; //其他人的ID
  17. public static byte[] bytes;
  18. // public static byt ta;
  19. QTTManager qt;
  20. // Start is called before the first frame update
  21. void Start()
  22. {
  23. // 请求文件读取和写入权限
  24. if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead) ||
  25. !Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
  26. {
  27. Permission.RequestUserPermission(Permission.ExternalStorageRead);
  28. Permission.RequestUserPermission(Permission.ExternalStorageWrite);
  29. }
  30. bytes = (Resources.Load("emqxsl-ca") as TextAsset).bytes;
  31. Debug.Log(" DGJ ===> emqxsl-ca.bytes "+ bytes.Length);
  32. }
  33. Queue<MqttMsgPublishEventArgs> rlist = new Queue<MqttMsgPublishEventArgs>();
  34. private void OnReceived(MqttMsgPublishEventArgs obj)
  35. {
  36. rlist.Enqueue(obj);
  37. }
  38. private void OnConnecting()
  39. {
  40. Debug.Log("MQtt 连接中");
  41. }
  42. private void onSucceed()
  43. {
  44. Subscribe();
  45. }
  46. private void onFaild()
  47. {
  48. Debug.Log("MQtt 连接失败");
  49. }
  50. // Update is called once per frame
  51. void Update()
  52. {
  53. if (rlist.Count > 0)
  54. {
  55. for (int i = 0; i < rlist.Count; i++)
  56. {
  57. OnUnityReceived(rlist.Dequeue());
  58. }
  59. }
  60. }
  61. //MQTT接收到的数据
  62. public void OnUnityReceived(MqttMsgPublishEventArgs obj)
  63. {
  64. string msg = Encoding.UTF8.GetString(obj.Message);
  65. Debug.Log("uid => " + obj.Topic + ":\n" + msg);
  66. try
  67. {
  68. JsonData data = JsonMapper.ToObject(msg);
  69. Debug.Log(" DGJ === > " + data["type"].ToString());
  70. switch (data["type"].ToString())
  71. {
  72. case "CamPos":
  73. Debug.Log("DGJ ===> CamPos");
  74. // 根据 uid 同步Player 位置 如果没有就创建
  75. MultiPlayerManager.Instance.ReceivedCamPos(obj.Topic, data);
  76. break;
  77. case "ActiveSp":
  78. // 同步对应景点的开关
  79. MultiPlayerManager.Instance.ReceivedActiveSp( data);
  80. break;
  81. case "ActiveVideo":
  82. // 同步播放器的对应状态
  83. MultiPlayerManager.Instance.ReceivedActiveVideo(data);
  84. break;
  85. default:
  86. break;
  87. }
  88. }
  89. catch
  90. {
  91. return;
  92. }
  93. }
  94. private void OnDestroy()
  95. {
  96. DisConnect();
  97. }
  98. public void SetUserName(string username)
  99. {
  100. if (username != null)
  101. this.username = username;
  102. }
  103. public void SetFront(string front)
  104. {
  105. if (front != null)
  106. this.front = front;
  107. }
  108. //连接
  109. public void Connect()
  110. {
  111. Debug.Log("DGJ ===> MQTT ");
  112. if (DeviceType.type == "Phone")
  113. {
  114. id =UserInfo.Instance.Account + "_Phone";
  115. rid = front+UserInfo.Instance.Account + "_Glasses";
  116. }
  117. else
  118. {
  119. id = UserInfo.Instance.Account + "_Glasses";
  120. rid = front+UserInfo.Instance.Account + "_Phone";
  121. }
  122. DisConnect();
  123. qt = new QTTManager(front+id, username, password, HttpAction.Instance.mqtturl, HttpAction.Instance.officeport);
  124. qt.Connect();
  125. StartCoroutine(Reconnection());
  126. qt.ConnectionFailed += onFaild;
  127. qt.ConnectionSucceeded += onSucceed;
  128. qt.OnConnecting += OnConnecting;
  129. qt.OnReceived += OnReceived;
  130. qt.OnClose += OnClose;
  131. }
  132. private void OnClose(EventArgs obj)
  133. {
  134. Debug.Log("断开连接");
  135. }
  136. private IEnumerator Reconnection()
  137. {
  138. while (true)
  139. {
  140. yield return new WaitForSeconds(5);
  141. if(qt!=null&&!qt.IsConnect())
  142. {
  143. Debug.Log(" DGJ ===> Reconnection ");
  144. Connect();
  145. }
  146. }
  147. }
  148. //断开连接
  149. public void DisConnect()
  150. {
  151. if (qt != null && qt.IsConnect())
  152. qt.DisConnect();
  153. }
  154. //订阅
  155. public void Subscribe()
  156. {
  157. Debug.Log(" DGJ =====> Subscribe "+ id);
  158. ushort s = qt.Subscribe(
  159. new string[]
  160. {
  161. front+id
  162. },
  163. new byte[]
  164. {
  165. MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE
  166. });
  167. Debug.Log(" DGJ =====> Subscribe2");
  168. }
  169. public void StartSendCameraPos()
  170. {
  171. StartCoroutine(sendCameraPos());
  172. }
  173. //眼镜端像手机端发送实时位置
  174. IEnumerator sendCameraPos()
  175. {
  176. Debug.Log("DGJ =====> sendCameraPos" + qt.IsConnect());
  177. while (true)
  178. {
  179. if(qt!=null&& qt.IsConnect())
  180. {
  181. JsonData json = new JsonData();
  182. json["type"] = "CamPos";
  183. // json["x"] = OpenXRCamera.Instance.head.position.x;
  184. //json["y"] = OpenXRCamera.Instance.head.position.y;
  185. //json["z"] = OpenXRCamera.Instance.head.position.z;
  186. json["x"] = GameManager.Instance.Player.transform.localPosition.x;
  187. json["y"] = GameManager.Instance.Player.transform.localPosition.y;
  188. json["z"] = GameManager.Instance.Player.transform.localPosition.z;
  189. json["Sid"] = "sid";//选择的场景id
  190. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  191. }
  192. yield return new WaitForSeconds(0.1f);
  193. }
  194. }
  195. //眼镜发送触发的景点
  196. public void sendActiveSp(string spid,bool isOpen)
  197. {
  198. JsonData json = new JsonData();
  199. json["type"] = "ActiveSp";
  200. json["Sid"] = "sid";//选择的场景id
  201. json["spid"] = spid;//景点id
  202. json["isOpen"] = isOpen;//是否打开
  203. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  204. Debug.Log("MQtt 发送manage");
  205. }
  206. //眼镜发送触发的视频
  207. public void sendActiveVideo(string spid,string videoId, bool isplay,float jindu)
  208. {
  209. JsonData json = new JsonData();
  210. json["type"] = "ActiveVideo";
  211. json["Sid"] = "sid";//选择的场景id
  212. json["spid"] = spid;//景点id
  213. json["videoId"] = videoId;//视频id
  214. json["isplay"] = isplay;//是否播放
  215. json["jindu"] = jindu;//视频进度
  216. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  217. Debug.Log("MQtt 发送manage");
  218. }
  219. void publish(byte[] bs)
  220. {
  221. if(qt!=null&& qt.IsConnect())
  222. {
  223. Debug.Log(id + " DGJ publish =====> " + front+rid + " " + bs.Length);
  224. qt.Publish(rid, bs, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
  225. }
  226. else
  227. {
  228. Debug.LogError(" MQTT 未连接 ");
  229. }
  230. }
  231. }