MQTTClient.cs 6.8 KB

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