MQTTClient.cs 8.4 KB

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