MQTTClient.cs 7.6 KB

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