MQTTClient.cs 8.6 KB

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