MQTTClient.cs 7.9 KB

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