MQTTClient.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. //连接
  104. public void Connect()
  105. {
  106. Debug.Log("DGJ ===> MQTT ");
  107. if (DeviceType.type == "Phone")
  108. {
  109. id =UserInfo.Instance.Account + "_Phone";
  110. rid = UserInfo.Instance.Account + "_Glasses";
  111. }
  112. else
  113. {
  114. id = UserInfo.Instance.Account + "_Glasses";
  115. rid = UserInfo.Instance.Account + "_Phone";
  116. }
  117. DisConnect();
  118. qt = new QTTManager(id, username, password);
  119. qt.Connect();
  120. StartCoroutine(Reconnection());
  121. qt.ConnectionFailed += onFaild;
  122. qt.ConnectionSucceeded += onSucceed;
  123. qt.OnConnecting += OnConnecting;
  124. qt.OnReceived += OnReceived;
  125. qt.OnClose += OnClose;
  126. }
  127. private void OnClose(EventArgs obj)
  128. {
  129. Debug.Log("断开连接");
  130. }
  131. private IEnumerator Reconnection()
  132. {
  133. while (true)
  134. {
  135. yield return new WaitForSeconds(5);
  136. if(qt!=null&&!qt.IsConnect())
  137. {
  138. Debug.Log(" DGJ ===> Reconnection ");
  139. Connect();
  140. }
  141. }
  142. }
  143. //断开连接
  144. public void DisConnect()
  145. {
  146. if (qt != null && qt.IsConnect())
  147. qt.DisConnect();
  148. }
  149. //订阅
  150. public void Subscribe()
  151. {
  152. Debug.Log(" DGJ =====> Subscribe "+ id);
  153. ushort s = qt.Subscribe(
  154. new string[]
  155. {
  156. id
  157. },
  158. new byte[]
  159. {
  160. MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE
  161. });
  162. Debug.Log(" DGJ =====> Subscribe2");
  163. }
  164. public void StartSendCameraPos()
  165. {
  166. StartCoroutine(sendCameraPos());
  167. }
  168. //眼镜端像手机端发送实时位置
  169. IEnumerator sendCameraPos()
  170. {
  171. Debug.Log("DGJ =====> sendCameraPos" + qt.IsConnect());
  172. while (true)
  173. {
  174. if(qt!=null&& qt.IsConnect())
  175. {
  176. JsonData json = new JsonData();
  177. json["type"] = "CamPos";
  178. // json["x"] = OpenXRCamera.Instance.head.position.x;
  179. //json["y"] = OpenXRCamera.Instance.head.position.y;
  180. //json["z"] = OpenXRCamera.Instance.head.position.z;
  181. json["x"] = GameManager.Instance.Player.transform.localPosition.x;
  182. json["y"] = GameManager.Instance.Player.transform.localPosition.y;
  183. json["z"] = GameManager.Instance.Player.transform.localPosition.z;
  184. json["Sid"] = "sid";//选择的场景id
  185. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  186. }
  187. yield return new WaitForSeconds(0.1f);
  188. }
  189. }
  190. //眼镜发送触发的景点
  191. public void sendActiveSp(string spid,bool isOpen)
  192. {
  193. JsonData json = new JsonData();
  194. json["type"] = "ActiveSp";
  195. json["Sid"] = "sid";//选择的场景id
  196. json["spid"] = spid;//景点id
  197. json["isOpen"] = isOpen;//是否打开
  198. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  199. Debug.Log("MQtt 发送manage");
  200. }
  201. //眼镜发送触发的视频
  202. public void sendActiveVideo(string spid,string videoId, bool isplay,float jindu)
  203. {
  204. JsonData json = new JsonData();
  205. json["type"] = "ActiveVideo";
  206. json["Sid"] = "sid";//选择的场景id
  207. json["spid"] = spid;//景点id
  208. json["videoId"] = videoId;//视频id
  209. json["isplay"] = isplay;//是否播放
  210. json["jindu"] = jindu;//视频进度
  211. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  212. Debug.Log("MQtt 发送manage");
  213. }
  214. void publish(byte[] bs)
  215. {
  216. if(qt!=null&& qt.IsConnect())
  217. {
  218. Debug.Log(id + " DGJ publish =====> " + rid + " " + bs.Length);
  219. qt.Publish(rid, bs, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
  220. }
  221. else
  222. {
  223. Debug.LogError(" MQTT 未连接 ");
  224. }
  225. }
  226. }