MQTTClient.cs 8.3 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. //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(MQTTManager.Instance.front + "online/" + MQTTManager.Instance.phone);
  56. Subscribe(MQTTManager.Instance.front + "personnel/" + MQTTManager.Instance.resourcePool);
  57. Subscribe(MQTTManager.Instance.front + "online/" + MQTTManager.Instance.phone);
  58. }
  59. private void onFaild()
  60. {
  61. Debug.Log("MQtt 连接失败");
  62. }
  63. // Update is called once per frame
  64. void Update()
  65. {
  66. if (rlist.Count > 0)
  67. {
  68. for (int i = 0; i < rlist.Count; i++)
  69. {
  70. OnUnityReceived(rlist.Dequeue());
  71. }
  72. }
  73. }
  74. //MQTT接收到的数据
  75. public void OnUnityReceived(MqttMsgPublishEventArgs obj)
  76. {
  77. string msg = Encoding.UTF8.GetString(obj.Message);
  78. Debug.Log("uid => " + obj.Topic + ":\n" + msg);
  79. // UILogManager.Instance.text3.text = msg;
  80. MQTTManager.Instance.Received(msg);
  81. }
  82. private void OnDestroy()
  83. {
  84. DisConnect();
  85. }
  86. //连接
  87. public void Connect()
  88. {
  89. Debug.Log("DGJ ===> MQTT " + HttpActionLang.Instance.mqttSocket );
  90. //if (DeviceType.type == "Phone")
  91. //{
  92. // id =UserInfo.Instance.name + "_Phone";
  93. // rid = front+UserInfo.Instance.name + "_Glasses";
  94. //}
  95. //else
  96. //{
  97. // id = UserInfo.Instance.name + "_Glasses";
  98. // rid = front+UserInfo.Instance.name + "_Phone";
  99. //}
  100. // Debug.Log("DGJ ==>MQTT " + id + account + " " + username + " " + certification + " " + HttpActionLang.Instance.mqttSocket);
  101. DisConnect();
  102. qt = new QTTManager(MQTTManager.Instance.id, MQTTManager.Instance.username , MQTTManager.certification, HttpActionLang.Instance.mqttSocket, "1883");
  103. qt.Connect();
  104. StartCoroutine(Reconnection());
  105. qt.ConnectionFailed += onFaild;
  106. qt.ConnectionSucceeded += onSucceed;
  107. qt.OnConnecting += OnConnecting;
  108. qt.OnReceived += OnReceived;
  109. qt.OnClose += OnClose;
  110. // StartSendCameraPos();
  111. }
  112. private void OnClose(EventArgs obj)
  113. {
  114. Debug.Log("断开连接");
  115. }
  116. private IEnumerator Reconnection()
  117. {
  118. while (true)
  119. {
  120. yield return new WaitForSeconds(5);
  121. if (qt != null && !qt.IsConnect())
  122. {
  123. Debug.Log(" DGJ ===> Reconnection ");
  124. Connect();
  125. }
  126. }
  127. }
  128. //断开连接
  129. public void DisConnect()
  130. {
  131. if (qt != null && qt.IsConnect())
  132. qt.DisConnect();
  133. }
  134. /// <summary>
  135. /// 订阅频道
  136. /// </summary>
  137. /// <param name="channelID"></param>
  138. public void Subscribe(string channelID)
  139. {
  140. Debug.Log(" DGJ =====> Subscribe " + channelID);
  141. if (qt != null && qt.IsConnect())
  142. {
  143. ushort s = qt.Subscribe(
  144. new string[]
  145. {
  146. channelID
  147. //front+"room/"+roomId
  148. },
  149. new byte[]
  150. {
  151. MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE,
  152. //MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE
  153. });
  154. Debug.Log(" DGJ =====> Subscribe2");
  155. }
  156. else
  157. Debug.LogError(" MQTT 未连接 !!!");
  158. }
  159. public void StartSendCameraPos()
  160. {
  161. StartCoroutine(sendCameraPos());
  162. }
  163. //眼镜端像手机端发送实时位置
  164. IEnumerator sendCameraPos()
  165. {
  166. Debug.Log("DGJ =====> sendCameraPos" + qt.IsConnect());
  167. while (true)
  168. {
  169. yield return new WaitForSeconds(1f);
  170. if (qt != null && qt.IsConnect())
  171. {
  172. JsonData json = new JsonData();
  173. json["type"] = "CamPos";
  174. // json["x"] = OpenXRCamera.Instance.head.position.x;
  175. //json["y"] = OpenXRCamera.Instance.head.position.y;
  176. //json["z"] = OpenXRCamera.Instance.head.position.z;
  177. //json["x"] = GameManager.Instance.Player.transform.localPosition.x;
  178. //json["y"] = GameManager.Instance.Player.transform.localPosition.y;
  179. //json["z"] = GameManager.Instance.Player.transform.localPosition.z;
  180. json["Sid"] = "sid";//选择的场景id
  181. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  182. }
  183. }
  184. }
  185. //眼镜发送触发的景点
  186. public void sendActiveSp(string spid, bool isOpen)
  187. {
  188. JsonData json = new JsonData();
  189. json["type"] = "ActiveSp";
  190. json["Sid"] = "sid";//选择的场景id
  191. json["spid"] = spid;//景点id
  192. json["isOpen"] = isOpen;//是否打开
  193. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  194. Debug.Log("MQtt 发送manage");
  195. }
  196. //眼镜发送触发的视频
  197. public void sendActiveVideo(string spid, string videoId, bool isplay, float jindu)
  198. {
  199. JsonData json = new JsonData();
  200. json["type"] = "ActiveVideo";
  201. json["Sid"] = "sid";//选择的场景id
  202. json["spid"] = spid;//景点id
  203. json["videoId"] = videoId;//视频id
  204. json["isplay"] = isplay;//是否播放
  205. json["jindu"] = jindu;//视频进度
  206. publish(Encoding.UTF8.GetBytes(json.ToJson()));
  207. Debug.Log("MQtt 发送manage");
  208. }
  209. public void SendCoord()
  210. {
  211. JsonData json = new JsonData();
  212. json["id"] = UserInfo.Instance.name;
  213. json["type"] = "Coord";
  214. json["x"] = 0.1f;
  215. json["y"] = 0.1f;
  216. json["z"] = 0.1f;
  217. }
  218. public void publish(byte[] bs)
  219. {
  220. if (qt != null && qt.IsConnect())
  221. {
  222. // Debug.Log(id + account + " DGJ publish =====> " + front + "room/" + roomId + " " + bs.Length);
  223. // qt.Publish(front + "room/" + roomId, bs, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
  224. }
  225. else
  226. {
  227. Debug.LogError(" MQTT 未连接 ");
  228. }
  229. }
  230. public void publish(string channelID, byte[] bs)
  231. {
  232. if (qt != null && qt.IsConnect())
  233. {
  234. Debug.Log(MQTTManager.Instance.id + MQTTManager.Instance.account + " DGJ publish =====> " + channelID + " " + bs.Length);
  235. qt.Publish(channelID, bs, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
  236. }
  237. else
  238. {
  239. Debug.LogError(" MQTT 未连接 ");
  240. }
  241. }
  242. }